英文:
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:"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)
}
Output is (https://play.golang.org/p/kyG1YabpSe):
{"Foo":"Foo","bar":{"zip":"35000"}}
Even with a 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)
}
https://play.golang.org/p/qCsmAGzo4H
Output is good, i don't understand where you are wrong.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论