我有一个可以根据 HTTP 请求 header 输出为 JSON 或 XML 的应用程序。我可以通过将正确的标签添加到我正在使用的结构中来实现正确的输出,但我不知道如何为 JSON 和 XML 指定标签。
例如,这将序列化为正确的 XML:
type Foo struct {
Id int64 `xml:"id,attr"`
Version int16 `xml:"version,attr"`
}
...这会生成正确的 JSON:
type Foo struct {
Id int64 `json:"id"`
Version int16 `json:"version"`
}
...但这对任何一个都不起作用:
type Foo struct {
Id int64 `xml:"id,attr",json:"id"`
Version int16 `xml:"version,attr",json:"version"`
}
最佳答案
Go 标记以空格分隔。来自 the manual :
By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.
那么,你要写的是:
type Foo struct {
Id int64 `xml:"id,attr" json:"id"`
Version int16 `xml:"version,attr" json:"version"`
}
关于Golang 结构的 XML 和 JSON 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885162/