我希望使用 "encoding/json"
包来编码在我的应用程序的一个导入包中声明的结构。
例如:
type T struct {
Foo int
}
因为它是导入的,所以结构中所有可用(导出)的字段都以大写字母开头。但我希望有小写的键名:
out, err := json.Marshal(&T{Foo: 42})
会导致
{"Foo":42}
但我想得到
{"foo":42}
是否有可能以某种简单的方式解决这个问题?
最佳答案
查看 encoding/json.Marshal 的文档. 它讨论了使用 struct 字段标签来确定生成的 json 的格式。
例如:
type T struct {
FieldA int `json:"field_a"`
FieldB string `json:"field_b,omitempty"`
}
这将生成如下 JSON:
{
"field_a": 1234,
"field_b": "foobar"
}
https://stackoverflow.com/questions/11693865/