duanfan5012 2018-05-06 10:32
浏览 258
已采纳

解码数组时无法将数组解编为Go结构

I'm trying to properly decode JSON String to an object.

I defined the following structs:

type AjaxModelsList struct {
    Id float64 `json:"Id"`
    Name string `json:"Name"`
    CarId float64 `json:"CarId"`
    EngName string `json:"EngName"`
}

type AjaxModelsData struct {
    ModelList []AjaxModelsList `json:"ModelList"`
}

type AjaxModels struct {
    Status bool `json:"status"`
    Data map[string]AjaxModelsData `json:"data"`

}

the defined object is

{
 "status": true,
 "data": {
 "ModelList": [{
   "Id": 1,
   "Name": "foo",
   "CarId": 1,
   "EngName": "bar"
  }]
 }
}

and I unmarshall using the following code:

c :=AjaxModels{}
if err := json.Unmarshal(body_byte,&c); err != nil {
    log.Fatalf("an error occured: %v",err)
}

and I get the following output:

an error occured: json: cannot unmarshal array into Go struct field AjaxModels.data of type main.AjaxModelsData

since I used []AjaxModelsList it's a slice so I shouldn't be getting this error. I probably missed something, but what ?

  • 写回答

1条回答 默认 最新

  • duanlu0075 2018-05-06 13:18
    关注

    In the json the data structure is object[key]array, while in Go Data is map[key]struct.slice. Change Data to be map[key]slice instead.

    E.g.

    type AjaxModels struct {
        Status bool                      `json:"status"`
        Data   map[string][]AjaxModelsList `json:"data"`
    }
    

    https://play.golang.org/p/Sh_vKVL-D--

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line