dongyun3335 2017-02-24 15:19
浏览 53
已采纳

JSON解码未知对象

I'm trying to decode a json response with a struct type. An instance of the object i'm trying to decode looks as follows:

{
  "title": "Some Title",
  "views": 344,
  "profiles": {
      "customField": "somevalue",
      "customField2:" :somevalue"
  }
}

The golang struct is the following:

type Topic struct {
  Title         string   `json:"title"`
  Views         string   `json:"views"`
  Profiles      string   `json:"profiles"`
}

As you can see, the "Profiles" attribute is a string, since the profiles object is unknown, as the fields inside it can be dinamically defined.

I'm trying to decode this with:

json.NewDecoder(response.Body).Decode(result) 

Where result is of type Topic, but isn't working. What type should the "Profiles" attribute be in order to correctly decoding the answer?

Thanks!

  • 写回答

4条回答 默认 最新

  • doulifang5554 2017-02-24 15:33
    关注

    Reading the comment it's clear that profiles value could be of any type, for this reason I suggest you to declare the Profiles type as a map[string]interface{}.
    Topic becomes:

    type Topic struct {
      Title         string   `json:"title"`
      Views         int32   `json:"views"`
      Profiles      map[string]interface{}   `json:"profiles"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路