doulu4534 2017-06-30 09:07
浏览 73
已采纳

Golang将JSON映射到结构

I have a struct as below:

type Item struct {
  ID         int16 `json:"id"`
  SubItem    *Item `json:"sub_item"`
}

And the JSON as below:

{
  "id": 100,
  "sub_item": 110
}

If I use json.Unmarshal(json, &item), the json field sub_item is the Item.ID, so cannot mapping into struct.

I want to find the SubItem by the subitem id before json unmarshal, but I don't know how to do it. Or is there any way to resolve this problem? thanks a lot.

  • 写回答

1条回答 默认 最新

  • dongxia527680 2017-06-30 09:30
    关注

    *Item is a golang pointer to a struct. It cannot contain a int16 (that is a "pointer" in your json semantic).

    You can handle this programmatically after Unmarshaling.

    Struct must be:

    type Item struct {
        ID         int16 `json:"id"`
        SubItem    *Item
        SubItemInt int16 `json:"sub_item"`
    }
    

    and then you should do something like this:

    items := make(map[int16]*Item)
    [...]
    for k := range items {
        items[k].SubItem = items[items[k].SubItemInt]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳