【问题标题】:Complex JSON marshaling to GoLang objects复杂的 JSON 编组到 GoLang 对象
【发布时间】:2016-07-07 10:57:04
【问题描述】:

我需要将复杂的 JSON 对象编组为 GO 结构。

所以我有来源:

"NetworkSettings": {
        "Bridge": "",
        "SandboxID": "e9736755bc41db307019fde3be0feed51086e6d3e23b0213c59bb5e43f7af214",
        "HairpinMode": false,
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "2ee283787f45894c3383229d29ada1ccbb7f34b1c1e143e417e7ba75b7f5ebce",
        "Gateway": "172.17.0.1",
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "MacAddress": "02:42:ac:11:00:02",
        "Networks": {
            "bridge": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": null,
                "NetworkID": "1c4788fac19973ddc73975613a2aef5a4cc2be446af458c06fa5fa162e8126ff",
                "EndpointID": "2ee283787f45894c3383229d29ada1ccbb7f34b1c1e143e417e7ba75b7f5ebce",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02"
            }
        }

我需要将它映射到这样的对象中:

NetworkSettings struct {
    IpAddress string
    SandboxID string
    Gateway string
    Ports     map[string][]Binding
    Networks map[string]map[string]string
}

但是因为Networks map[string]map[string]string我得到了错误

json: cannot unmarshal object into Go value of type string
error restoring containers: json: cannot unmarshal object into Go value of type string

但这正是我需要拥有一个复杂的地图结构的地图。

知道怎么做吗?

【问题讨论】:

    标签: json go


    【解决方案1】:

    发生该错误是因为 JSON 中的某些值不是字符串,而是整数(例如IPPrefixLen),因此不能分配给字符串变量。

    有两种方法可以解决这个问题。您可以使用 interface{} 类型,因此您的类型定义将变为:

    NetworkSettings struct {
        IpAddress string
        SandboxID string
        Gateway   string
        Ports     map[string][]Binding
        Networks  map[string]map[string]interface{}
    }
    

    更好的解决方案可能是为 Network 块定义一个类型:

    type Network struct {
        NetworkID   string 
        EndpointID  string
        Gateway     string
        IPAddress   string
        IPPrefixLen int
        //etc...
    }
    type NetworkSettings struct {
        IpAddress string
        SandboxID string
        Gateway   string
        Ports     map[string][]Binding
        Networks  map[string]Network
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2020-03-08
      • 2015-10-25
      • 2014-04-25
      • 2015-06-10
      相关资源
      最近更新 更多