英文:
JSON Decoder cannot decode an object into an object
问题
以下是翻译好的内容:
type MiddleMan struct {
User CompletedByUser `json:"user"`
}
type CompletedByUser struct {
DisplayName string `json:"displayName"`
Id string `json:"id"`
}
使用上述类型,我运行了以下代码:
shorterJsonString := `{
"user":{
"displayName":null,
"id":"a03dfee5-a754-4eb9"
}
}`
if !json.Valid([]byte(shorterJsonString)) {
log.Println("Not valid")
}
var middleMan models.MiddleMan
newReader := strings.NewReader(shorterJsonString)
json.NewDecoder(newReader).Decode(&middleMan)
log.Println(middleMan)
不幸的是,解码器似乎对嵌套对象有问题。打印输出的结果是:
{{ a03dfee5-a754-4eb9 }}
它似乎将整个对象扁平化为id字段。这是怎么回事?
英文:
type MiddleMan struct {
User CompletedByUser `json:"user"`
}
type CompletedByUser struct {
DisplayName string `json:"displayName"`
Id string `json:"id"`
}
Using the following types, I run the code
shorterJsonString := `{
"user":{
"displayName":null,
"id":"a03dfee5-a754-4eb9"
}
}`
if !json.Valid([]byte(shorterJsonString)) {
log.Println("Not valid")
}
var middleMan models.MiddleMan
newReader := strings.NewReader(shorterJsonString)
json.NewDecoder(newReader).Decode(&middleMan)
log.Println(middleMan)
Unfortunately, the decoder is seemingly broken for nested objects. Rather than spitting out actual objects, the print prints out
{{ a03dfee5-a754-4eb9 }}
It seems to flatten the whole thing into the id field. What is going on here?
答案1
得分: 4
你期望发生什么/打印什么?
log
包(使用 fmt
包)会打印用大括号括起来的结构体,字段值之间用空格分隔。
你的 MiddleMan
结构体只有一个字段,所以它看起来会像这样:
{field}
其中 field
是另一个类型为 CompletedByUser
的 struct
,它有两个字段,所以它看起来会像这样:
{{field1 field2}}
其中 field
是 string
类型,是空字符串,所以你会看到 field2
的值前面有一个空格:
{{ a03dfee5-a754-4eb9}}
如果你打印时添加字段名:
log.Printf("%+v", middleMan)
你会看到如下输出:
{User:{DisplayName: Id:a03dfee5-a754-4eb9}}
使用另一种(Go 语法)格式:
log.Printf("%#v", middleMan)
输出:
main.MiddleMan{User:main.CompletedByUser{DisplayName:"", Id:"a03dfee5-a754-4eb9"}}
你可以在 Go Playground 上尝试这个。
英文:
What did you expect to happen / get printed?
The log
package (which uses the fmt
package) prints structs enclosed in braces, listing field values separated by spaces.
Your MiddleMan
has a single field, so it'll look like this:
{field}
Where field
is another struct
of type CompletedByUser
, which has 2 fields, so it'll look like this:
{{field1 field2}}
Where field
is of string
type, being the empty string, so you'll see the value of field2
prefixed with a space:
{{ a03dfee5-a754-4eb9}}
If you print it adding field names:
log.Printf("%+v", middleMan)
You'll see an output like:
{User:{DisplayName: Id:a03dfee5-a754-4eb9}}
Using another (Go-syntax) format:
log.Printf("%#v", middleMan)
Output:
main.MiddleMan{User:main.CompletedByUser{DisplayName:"", Id:"a03dfee5-a754-4eb9"}}
Try this on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论