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 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用