简体   繁体   中英

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.

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. I have no Idea, how to represent Users multidimensional array inside struct

In the json the Users key is an array and so the corresponding Go field should be a slice.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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