英文:
Why struct fields are showing empty?
问题
我正在努力从以下代码中获得正确的输出:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob3 = []byte(`[
{"name": "Platypus", "spec": "Monotremata", "id":25 },
{"name": "Quoll", "spec": "Dasyuromorphia", "id":25 }
]`)
type Animal2 struct {
name string
spec string
id uint32
}
var animals []Animal2
err := json.Unmarshal(jsonBlob3, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", animals)
}
当打印时,结构体字段为空。我确定有一个愚蠢的错误,但我对Go还很陌生,我已经卡在这里几个小时了。请帮忙。
英文:
I am struggling to get the correct output from the following code:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var jsonBlob3 = []byte(`[
{"name": "Platypus", "spec": "Monotremata", "id":25 },
{"name": "Quoll", "spec": "Dasyuromorphia", "id":25 }
]`)
type Animal2 struct {
name string
spec string
id uint32
}
var animals []Animal2
err := json.Unmarshal(jsonBlob3, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", animals)
}
Playground snippet
The struct fields are empty when printed. I am sure there is a dumb mistake somewhere but I am still new to Go and I have been stuck at this for hours. Please help.
答案1
得分: 11
这个问题已经出现了很多次。问题在于只有导出的字段才能进行编组/解组。
通过将结构体字段以大写字母开头来导出它们。
type Animal2 struct {
Name string
Spec string
Id uint32
}
在Go Playground上试一试。
请注意,JSON文本中的字段名包含小写字母,但json
包足够“聪明”,可以匹配它们。如果它们完全不同,您可以使用结构标签告诉json
包它们在JSON文本中的位置(或者应该如何进行编组),例如:
type Animal2 struct {
Name string `json:"json_name"`
Spec string `json:"specification"`
Id uint32 `json:"some_custom_id"`
}
英文:
This has come up so many times. The problem is that only exported fields can be marshaled/unmarshaled.
Export the struct fields by starting them with capital (upper-case) letters.
type Animal2 struct {
Name string
Spec string
Id uint32
}
Try it on the Go Playground.
Note that the JSON text contains the field names with lowercased text, but the json
package is "clever" enough to match them. If they would be completely different, you could use struct tags to tell the json
package how they are found (or how they should be marshaled) in the JSON text, e.g.:
type Animal2 struct {
Name string `json:"json_name"`
Spec string `json:"specification"`
Id uint32 `json:"some_custom_id"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论