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 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题