Golang 结构的 XML 和 JSON 标签?

标签 xml json encoding go

我有一个可以根据 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/

相关文章:

ios - 从 JSON 响应中获取字典数组中的数据

encoding - 如何在Python 2上更改stdin和stdout编码

asp.net - 如何使用 ASP.NET 注入(inject)包含 & 符号的脚本 URL?

xml - 使用 xpath 删除节点

java - 在运行时通过加载模式验证 XML,失败取决于模式顺序

c++ - MSXML 是如何工作的? (进程内 COM 对象的工作原理)

python - 如何在Python中解码日元符号?

c# - 如何在 Web API 响应中排除 Xml 序列化中的属性名称

javascript - 如何使用 jquery 或 javascript 重新定位 JSON 中对象的键

javascript - getJSON 返回 null