【问题标题】:Why is my json.Marshal() returning nothing? [duplicate]为什么我的 json.Marshal() 什么也没返回? [复制]
【发布时间】: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的字段了。

标签: json go struct slice


【解决方案1】:

因为 json 只看到公共字段 - 例如以大写开头。

这样做:

type Topic struct {
    ID string `json:"id"`
}

topics := []Topic{
    {ID: "some identifier"},
    {ID: "some other identifier"},
}

【讨论】:

  • 我想你的意思是说“exported”而不是“public”。 Go 导出的概念不同于具有公共特性的编程语言中的公共概念。
  • 非常感谢!
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多