英文:
Go: Modelling general JSON arrays in a struct possible?
问题
我想要能够对结构体进行编组/解组
type MyType struct {
Items <这里放什么?> `json:"item"`
}
其中一个示例的JSON文档是
{"items":["value1", {"x":"y"}, "value3"]}
我刚开始学习Go。我开始觉得我可能需要对数组的结构施加一些限制。使用上面的示例,我的想法是
{"items":[
{"type":null, "value":"value1"}
{"type":"x", "value":"y"},
{"type": "value3", "value":"value3"}
]}
然后使用它们自己的结构对内部对象进行建模。我宁愿用第一种方式,这种方式可行吗?
英文:
I want to be able to Marshal/Unmarshall a struct
type MyType struct {
Items <What goes here?> `json:"item"`
}
Where an example JSON document it must be able to handle is
{"items":["value1", {"x":"y"}, "value3"]}
I am only starting to learn Go. I am starting to think I might need to impose some restrictions on the structure of the array. Using the above example, my idea would be
{"items":[
{"type":null, "value":"value1"}
{"type:"x", "value":"y"},
{"type": "value3", "value":"value3"}
]}
Then modelling the objects inside with their own struct. I'd rather do it the first way, is it possible?
答案1
得分: 0
你的Items必须是一个接口数组,像这样:
Items []interface{}
这是一个完整的示例:
http://play.golang.org/p/LOXCiSmUET
当你解析json并想要遍历你的Items时,你需要确定类型。当处理复杂类型时,它们被表示为**map[string]interface{}**而不是结构体,在这种情况下,你需要自己创建结构体。
英文:
your Items have to be an array of interface
like this:
Items []interface{}
here is a complete example:
http://play.golang.org/p/LOXCiSmUET
when you unmarshal your json, and want to iterate over your Items you need to identify the type. when doing be aware that complex types are represented as map[string]interface and not as struct, in such case your need to create the struct by your self
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论