【发布时间】:2021-11-26 00:13:11
【问题描述】:
我正在尝试创建具有以下结构的 JSON 对象片段:
[
{"id":"some identifier"},
{"id":"some other identifier"}
]
我的代码正在生成[{},{}]。为什么会这样?
代码如下:
type Topic struct {
id string
}
topics := []Topic{
{id: "some identifier"},
{id: "some other identifier"},
}
fmt.Println(topics) // prints the topics as is, before marshaling
tops, err := json.Marshal(topics)
if err != nil {
fmt.Println("got an error", err)
}
fmt.Println(string(tops)) // does not print the topics
【问题讨论】:
-
将
id导出,这样json marshaler就可以看到struct的字段了。