Go:在结构体中建模通用的JSON数组是否可能?

huangapple go评论82阅读模式
英文:

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    &lt;What goes here?&gt;   `json:&quot;item&quot;`
}

Where an example JSON document it must be able to handle is

{&quot;items&quot;:[&quot;value1&quot;, {&quot;x&quot;:&quot;y&quot;}, &quot;value3&quot;]}

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

{&quot;items&quot;:[
    {&quot;type&quot;:null, &quot;value&quot;:&quot;value1&quot;}
    {&quot;type:&quot;x&quot;, &quot;value&quot;:&quot;y&quot;},
    {&quot;type&quot;: &quot;value3&quot;, &quot;value&quot;:&quot;value3&quot;}
]}

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

huangapple
  • 本文由 发表于 2013年6月30日 02:42:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/17383554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定