在列表中使用不同类型去解组JSON [英] Unmarshal JSON in go with different types in a list

查看:73
本文介绍了在列表中使用不同类型去解组JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解组JSON结构:

I have trouble unmarschaling a JSON contruct:

{
  "id": 10,
  "result": [
    {
      "bundled": true,
      "type": "RM-J1100"
    },
    [
      {
        "name": "PowerOff",
        "value": "AAAAAQAAAAEAAAAvAw=="
      },
      {
        "name": "Input",
        "value": "AAAAAQAAAAEAAAAlAw=="
      }
    ]
  ]
}

我实际上需要结果中的第二个切片项目.

I actually need the second slice item from the result.

我目前的尝试是

type Codes struct {
    Id     int32      `json:"id"`
    Result []interface{} `json:"result"`
}

type ResultList struct {
    Info  InfoMap
    Codes []Code
}

type InfoMap struct {
    Bundled bool   `json:"bundled"`
    Type    string `json:"type"`
}

type Code struct {
    Name  string `json:"name"`
    Value string `json:"value"`
}

输出如下:

{10 {{false } []}}

但是我也尝试使用它:

type Codes struct {
    Id     int32      `json:"id"`
    Result []interface{} `json:"result"`
}

输出正常:

{10 [map[type:RM-J1100 bundled:true] [map[name:PowerOff value:AAAAAQAAAAEAAAAvAw==] map[name:Input value:AAAAAQAAAAEAAAAlAw==]]]}

我还可以引用Result [1]索引:

I can also reference the Result[1] index:

[map[name:PowerOff value:AAAAAQAAAAEAAAAvAw==] map[name:Input value:AAAAAQAAAAEAAAAlAw==]]

但是我无法将接口类型转换为任何其他匹配类型.谁能告诉我如何进行界面转换.哪种方法才是最佳".

But I fail to convert the interface type to any other Type which would match. Can anybody tell me how to do interface conversion. And what approach would be the "best".

推荐答案

一种选择是将顶级内容解组为

One option would be to unmarshal the top level thing into a slice of json.RawMessage initially.

然后遍历成员,并查看每个成员的第一个字符.如果它是一个对象,则将其解编为您的InfoMap标头结构,如果它是一个数组,则将其解编为一个Code结构的切片.

Then loop through the members, and look at the first character of each one. If it is an object, unmarshal that into your InfoMap header struct, and if it is an array, unmarshal it into a slice of the Code struct.

或者如果可以预测的话,只需将第一个成员解组为一个结构,将第二个成员解构为切片.

Or if it is predictable enough, just unmarshal the first member to the one struct and the second to a slice.

我制作了这种方法的游乐场示例.

type Response struct {
    ID        int               `json:"id"`
    RawResult []json.RawMessage `json:"result"`
    Header    *Header           `json:"-"`
    Values    []*Value          `json:"-"`
}

type Header struct {
    Bundled bool   `json:"bundled"`
    Type    string `json:"type"`
}

type Value struct {
    Name  string `json:"name"`
    Value string `json:"value"`
}

func main() {
    //error checks ommitted
    resp := &Response{}
    json.Unmarshal(rawJ, resp)
    resp.Header = &Header{}
    json.Unmarshal(resp.RawResult[0], resp.Header)
    resp.Values = []*Value{}
    json.Unmarshal(resp.RawResult[1], &resp.Values)
}

这篇关于在列表中使用不同类型去解组JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆