如何解组未知字段名称的JSON以构造 [英] How to unmarshal JSON with unknown fieldnames to struct
本文介绍了如何解组未知字段名称的JSON以构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以解组未知字段的JSON?该字段名称始终是不同的,但是结构是相同的. JSON是POST请求的结果.
Is it possible to unmarshal JSON with unknown field? That field name is always different, but the structure is the same. JSON is a result of POST request.
我的代码:
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[]}
}
推荐答案
如果您不知道键,只需使用一个映射,并且映射的值类型可能是描述该结构的结构:
Simply use a map if you don't know the key, and the value type of the map may be the struct describing the structure:
type mData struct {
KnownField1 [][5]int `json:"known_field_1"`
KnownField2 [][5]int `json:"known_field_2"`
KnownField3 [][5]int `json:"known_field_3"`
}
请注意,您必须导出字段才能使其正常工作!
Note that you must export the fields for this to work!
以及解编代码:
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)
}
输出(在游乐场上尝试):
map[unknown_field:{[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}]
unknown_field {[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}
查看相关问题:
这篇关于如何解组未知字段名称的JSON以构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文