我有一个可以根据 HTTP 请求标头输出为 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"`}
1 回答
温温酱
TA贡献1752条经验 获得超4个赞
Go 标签是用空格分隔的。从手册:
按照惯例,标签字符串是可选的空格分隔键:“值”对的串联。每个键都是一个非空字符串,由除空格 (U+0020 ' ')、引号 (U+0022 '"') 和冒号 (U+003A ':') 以外的非控制字符组成。每个值都用引号引起来使用 U+0022 '"' 字符和 Go 字符串文字语法。
所以,你想写的是:
type Foo struct {
Id int64 `xml:"id,attr" json:"id"`
Version int16 `xml:"version,attr" json:"version"`
}
- 1 回答
- 0 关注
- 271 浏览
添加回答
举报
0/150
提交
取消