duanhui5344 2018-05-16 05:38
浏览 26
已采纳

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

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

  • 写回答

1条回答

  • doumangzhen7204 2018-05-16 06:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题