ds122455 2016-02-01 02:18
浏览 129
已采纳

将包含动态键的REST API返回的JSON映射到Golang中的结构

I'm calling a REST API from my Go program which takes n number of hotel ids in the request and returns their data as a JSON. The response is like the following when say I pass 2 ids in the request, 1018089108070373346 and 2017089208070373346 :

{
 "data": {
  "1018089108070373346": {
    "name": "A Nice Hotel",
    "success": true
   },
  "2017089208070373346": {
    "name": "Another Nice Hotel",
    "success": true
   }
  }
}

Since I'm new to Golang I using a JSON Go tool available at http://mholt.github.io/json-to-go/ to get the struct representation for the above response. What I get is:

type Autogenerated struct {
    Data struct {
        Num1017089108070373346 struct {
            Name string `json:"name"`
            Success bool `json:"success"`
        } `json:"1017089108070373346"`
        Num2017089208070373346 struct {
            Name string `json:"name"`
            Success bool `json:"success"`
        } `json:"2017089208070373346"`
    } `json:"data"`
}

I cannot use the above struct because the actual id values and the number of ids I pass can be different each time, the JSON returned will have different keys. How can this situation be mapped to a struct ?

Thanks

  • 写回答

2条回答 默认 最新

  • dtm37893 2016-02-01 02:29
    关注

    Use a map:

    type Item struct {
        Name string `json:"name"`
        Success bool `json:"success"`
    } 
    type Response struct {
        Data map[string]Item `json:"data"`
    }
    

    <kbd>Run it on the playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题