如何在golang中解析带有未知字段名的JSON到struct?

时间:2018-03-19 12:10:42

标签: json go

是否可以用未知字段解组JSON?该字段名称总是不同,但结构是相同的。 JSON是POST请求的结果。

我的代码:

package main

import "fmt"
import "encoding/json"

var body = []byte(`{
    "unknown_field": {
            "known_field_1": [[1,2,3,4,5],[10,20,30,40,50],[100,200,300,400,500]],
            "known_field_2": [[11,21,31,41,51]],
            "known_field_3": [[12,22,32,42,52],[14,44,34,44,54]]
        }
}`)

type MyStruct struct {
    MainData map[string]mData `json:"-"`
}

type mData struct {
    knownField1 [][5]int `json:"known_field_1"`
    knownField2 [][5]int `json:"known_field_2"`
    knownField3 [][5]int `json:"known_field_3"`
}

func NewMyStruct() MyStruct {
    ms := MyStruct{}
    ms.MainData = make(map[string]mData)
    return ms
}

func main() {
    myStruct := NewMyStruct()
    if err := json.Unmarshal(body, &myStruct); err != nil {
        panic(err)
    }

    fmt.Println(myStruct) // gives {map[]}
}

1 个答案:

答案 0 :(得分:3)

如果您不知道密钥,只需使用地图,地图的值类型可以是描述结构的结构:

<DataGridTextColumn Binding="{Binding Value, Converter={StaticResource SetBitConverter}}"/>

请注意,您必须导出字段才能生效!

和解编码:

type mData struct {
    KnownField1 [][5]int `json:"known_field_1"`
    KnownField2 [][5]int `json:"known_field_2"`
    KnownField3 [][5]int `json:"known_field_3"`
}

输出(在Go Playground)上尝试:

var data map[string]mData
if err := json.Unmarshal(body, &data); err != nil {
    panic(err)
}

fmt.Println(data)
for k, v := range data {
    fmt.Println(k, v)
}

参见相关问题:

How to parse/deserlize a dynamic JSON in Golang

Unmarshal JSON with unknown fields

Unmarshal json string to a struct that have one element of the struct itself

JSON Nested dynamic structures Go decoding