dseslyh6662605 2017-03-15 21:02
浏览 39
已采纳

Golang中来自json的Struct的地图

So I am trying to parse a json into some structs and that works ok with the following:

type train struct {
 ID     string  `json:"id"`
 Price  float64 `json:"price,string"`
 Distance float64 `json:"Distance,string"`
}

type Station struct {
 ID       int64  `json:"id,string"`
 arrTrain []train`json:"arr"`
 depTrain []train`json:"dep"`
}

The problem, however, is that I would like to easily be able to reference the items in arrTrain and depTrain using their ID, so I think I need to change the Station struct to have arrTrain and depTrain as maps with the ID as the key. Is this possible when parsing the json or does it have to be 'post-processed'?

EDIT: As stated in one of the comments, unfortunately my json is in the following form:

{
  "id":1, 
  "arr": [
     {"id":"one","price":"$10.1","Distance":"100km"},
     {...}
  ],
  "dep":[
    {"id":"one","price":"$10.1","Distance":"100km"},
    {...}
  ]
}

In other words the ID is not on the outside of the json object and arrTrain is list.

  • 写回答

2条回答 默认 最新

  • douhu2525 2017-03-15 21:44
    关注

    Yes, you can define station like this:

    type Station struct {
        ID       int64            `json:"id,string"`
        arrTrain map[string]train `json:"arr"`
        depTrain map[string]train `json:"dep"`
    }
    

    And your JSON should like this

    {
      "id":1, 
      "arr": {
        "one":{"id":"one","price":"$10.1","Distance":"100km"},
        "two":...
      },
      "dep":{
        "one":{"id":"one","price":"$10.1","Distance":"100km"},
        "two":...
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(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时遇到的编译问题