将一个字段为另一个结构体的结构体转换为JSON。

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

Converting Struct to JSON where a field is another Struct

问题

我有两个结构体 struct:

type A struct {
    Zip string `json:"zip"`
}

type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
}

当我尝试对类型 B 进行 json.Marshal 时,Bar 字段没有正确转换。字段是正确的,但值始终为空。输出结果如下:

{"foo": "some-string-value", "bar": {"zip": ""}}

我做错了什么?

英文:

I have two structs struct:

type A struct {
    Zip string `json:"zip"`
}

type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
}

When I try to json.Marshal the B type, the Bar field does not get converted correctly. The fields are OK, but the values are always empty. The output looks like this:

{"foo": "some-string-value", "bar": {"zip": ""}}

What am I doing wrong?

答案1

得分: 4

你的A结构体中的Zip字段没有被填充。

type A struct {
    Zip string `json:"zip"`
}

type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
} 

func main() {
    one := A{"35000"}
    two := B{"Foo", one}
    json, _ := json.Marshal(two)
    fmt.Printf("%s\n", json)
}

输出结果为:

{"Foo":"Foo","bar":{"zip":"35000"}}

即使使用了map:

type A struct {
    Zip string `json:"zip"`
}
type B struct {
    Foo string `bson:"foo"`
    Bar A      `json:"bar"`
}
func main() {
    m := make(map[string]B)

    for x := 0; x < 10; x++ {
        m[strconv.Itoa(x)] = B{"Hello", A{"35000"}}
    }

    json, _ := json.Marshal(m)
    fmt.Printf("%s\n", json)
}

输出结果是正确的,我不明白你错在哪里。

英文:

Your Zip field in A is not populated.

type A struct {
	Zip string `json:&quot;zip&quot;`
}

type B struct {
	Foo string `bson:&quot;foo&quot;`
	Bar A      `json:&quot;bar&quot;`
} 
func main() {
    one := A{&quot;35000&quot;}
	two := B{&quot;Foo&quot;, one}
	json, _ := json.Marshal(two)
	fmt.Printf(&quot;%s\n&quot;, json)
}

Output is (https://play.golang.org/p/kyG1YabpSe):

{&quot;Foo&quot;:&quot;Foo&quot;,&quot;bar&quot;:{&quot;zip&quot;:&quot;35000&quot;}}

Even with a map

type A struct {
   Zip string `json:&quot;zip&quot;`
}
type B struct {
   Foo string `bson:&quot;foo&quot;`
   Bar A      `json:&quot;bar&quot;`
}
func main() {
   m := make(map[string]B)

   for x := 0; x &lt; 10; x++ {
	  m[strconv.Itoa(x)] = B{&quot;Hello&quot;, A{&quot;35000&quot;}}
   }

   json, _ := json.Marshal(m)
   fmt.Printf(&quot;%s\n&quot;, json)
}

https://play.golang.org/p/qCsmAGzo4H

Output is good, i don't understand where you are wrong.

huangapple
  • 本文由 发表于 2016年11月17日 15:57:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/40649466.html
匿名

发表评论

匿名网友

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

确定