duanchi1230 2018-02-21 07:49
浏览 31

如何将动态JSON响应映射到GO结构? [重复]

This question already has an answer here:

I am new to golang and trying to parse some response from a web service, and the response looks like:

[
  {
    "Data": {
      "KeyA": 1,
      "KeyB": 2
    },
    "Type": 0
  },
  {
    "Data": {
      "KeyX": "ValueX",
      "KeyY": 999
    },
    "Type": 1
  },
  {
    "Data": {
      "Val": 123,
      "Id": "999",
      "Cnt": 100
    },
    "Type": 2
  }
]

You can see that each element has a Key "Data" and "Type" (Must), but with different 'Type' comes the different 'Data' field.

Could you please suggest a efficiency way to construct this kind of response to Golang structure?

Thanks.

</div>
  • 写回答

1条回答 默认 最新

  • dpn4073 2018-02-21 07:53
    关注

    This should work for you

    type Test []struct {
        Data map[string]interface{} `json:"Data"`
        Type int `json:"Type"`
    }
    

    since the only variable keys and values are in Data, make that a map instead and look for the keys inside based on the type received

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制