【发布时间】:2016-11-22 18:24:46
【问题描述】:
如果您有以下 JSON 结构:
[
{
"type": "home",
"name": "house #1",
... some number of properties for home #1
},
{
"type": "bike",
"name": "trek bike #1",
... some number of properties for bike #1
},
{
"type": "home",
"name": "house #2",
... some number of properties for home #2
}
]
在解组对象之前,如何在不知道每种类型是什么的情况下在 Golang 中将其解码为结构。看来您必须进行两次解组。
据我所知,我可能应该使用 RawMessage 来延迟解码。但我不确定这会是什么样子。
假设我有以下结构:
type HomeType struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Bathrooms string `json:"bathrooms,omitempty"`
... more properties that are unique to a home
}
type BikeType struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Tires string `json:"tires,omitempty"`
... more properties that are unique to a bike
}
第二个问题。是否可以在流模式下执行此操作?什么时候这个数组真的很大?
谢谢
【问题讨论】:
-
如果有一个“类型”字段,并且所有属性都是字符串,为什么不直接解组到
[]map[string]string? -
想象一下 JSON 对象有很多属性,包括子对象和对象数组。
标签: json go struct stream unmarshalling