简体   繁体   English

如何在结构内部解组多维数组

[英]How to unmarshal multi dimensional array inside struct

I have following data:- 我有以下数据:

{"me":[{"id": "0xcfd","Title":"Story of Stackoverflow","Users":[{"id":"1","Name":"MetaBoss"},{"id":"2","Name":"Owner"}],"Tag":"golang,programming"}]}

and I have the following struct:- 而且我有以下结构:

type Root struct {
    ID string `json:"id,omitempty"`
    Title string `json:"Title,omitempty"`
    Myuser Users `json:"Users,omitempty"` // Users is struct
    Tag string `json:"Tag,omitempty"`
}

type Users struct {
    ID string `json:"id,omitempty"`
    Name string `json:"Name,omitempty"`
}

To unmarshal the data, I am trying to do following things - 为了解组数据,我正在尝试执行以下操作-

type Unmarh struct {
    Me []Root `json:"me"`
}

var r Unmarh
err = json.Unmarshal(response, &r)

while printing r.Me[0].Myuser , I am not able to get data. 在打印r.Me[0].Myuser ,我无法获取数据。

I am getting below error - 我遇到错误-

json: cannot unmarshal array into go struct field Root.Myuser of type User struct {....Users struct data}

It needs Myuser to be multidimensional array type and not Users struct. 它需要Myuser是多维array类型,而不是Users结构。 I have no Idea, how to represent Users multidimensional array inside struct 我不知道如何在struct内表示Users multidimensional array

In the json the Users key is an array and so the corresponding Go field should be a slice. 在json中, Users键是一个数组,因此对应的Go字段应为切片。

type Root struct {
    ID    string `json:"id,omitempty"`
    Title string `json:"Title,omitempty"`
    Users []User `json:"Users,omitempty"`
    Tag   string `json:"Tag,omitempty"`
}

https://play.golang.org/p/azE7kPFs02V https://play.golang.org/p/azE7kPFs02V

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM