在Go中解组不一致的JSON
我正在使用JSON,它返回三种不同的对象类型“items”、“categories”和“modifiers”。我为三种类型的对象创建了模型。但是,当我解组时,我选择了其中一种类型来解组整个JSON。(我知道这不是正确的方法…)然后,我尝试根据JSON字段“type”中标识的类型来解析不同的项,然后将该对象附加到适当类型的片段中。我有错误,因为我不知道如何对JSON进行解组,JSON中有不同的类型,有不同的字段 解组包含不同对象(每个对象都有各自的字段)的JSON的正确方法是什么 解决方案是创建一个包含所有可能字段的“超级模型”,然后对其进行解组吗 我还是个新手,希望你能给我一些建议。谢谢 如果实现,可以定义一个结构,将每个项类型解析为相关的结构 例如:在Go中解组不一致的JSON,json,go,unmarshalling,Json,Go,Unmarshalling,我正在使用JSON,它返回三种不同的对象类型“items”、“categories”和“modifiers”。我为三种类型的对象创建了模型。但是,当我解组时,我选择了其中一种类型来解组整个JSON。(我知道这不是正确的方法…)然后,我尝试根据JSON字段“type”中标识的类型来解析不同的项,然后将该对象附加到适当类型的片段中。我有错误,因为我不知道如何对JSON进行解组,JSON中有不同的类型,有不同的字段 解组包含不同对象(每个对象都有各自的字段)的JSON的正确方法是什么 解决方案是创建一
// Dynamic represents an item of any type.
type Dynamic struct {
Value interface{}
}
// UnmarshalJSON is called by the json package when we ask it to
// parse something into Dynamic.
func (d *Dynamic) UnmarshalJSON(data []byte) error {
// Parse only the "type" field first.
var meta struct {
Type string
}
if err := json.Unmarshal(data, &meta); err != nil {
return err
}
// Determine which struct to unmarshal into according to "type".
switch meta.Type {
case "product":
d.Value = &Product{}
case "post":
d.Value = &Post{}
default:
return fmt.Errorf("%q is an invalid item type", meta.Type)
}
return json.Unmarshal(data, d.Value)
}
// Product and Post are structs representing two different item types.
type Product struct {
Name string
Price int
}
type Post struct {
Title string
Content string
}
用法:
func main() {
// Parse a JSON item into Dynamic.
input := `{
"type": "product",
"name": "iPhone",
"price": 1000
}`
var dynamic Dynamic
if err := json.Unmarshal([]byte(input), &dynamic); err != nil {
log.Fatal(err)
}
// Type switch on dynamic.Value to get the parsed struct.
// See https://tour.golang.org/methods/16
switch dynamic.Value.(type) {
case *Product:
log.Println("got a product:", dynamic.Value)
case *Post:
log.Println("got a product:", dynamic.Value)
}
}
输出:
2009/11/10 23:00:00获得一个产品:&{iphone1000}
提示:如果您有一个动态对象列表,只需将其解析为
动态
:
var项[]动态
Unmarshal(`[{…},{…}]`,&items)
示例输出:
[&{iphone1000}&{Lorem ipsum之后的好文章…}]
我认为它也适合您的用例 你能给我们看看代码吗?