我有一个应用程序,可以根据HTTP请求头输出JSON或XML.通过将正确的标记添加到我使用的 struct 中,我可以实现这两种方法的正确输出,但我不知道如何为JSON和XML指定标记.

For example, this serializes to correct 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"`
}

...but this doesn't work for either:

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.

So, what you want to write is:

type Foo struct {
    Id          int64       `xml:"id,attr" json:"id"`
    Version     int16       `xml:"version,attr" json:"version"`
}

Json相关问答推荐

如何在VegaLite中应用Times New Roman,CaliBiri字体

在Reaction中从JSON文件中筛选数组

解析SQL中的嵌套JSON

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

使用 jq,如何将两个属性构成键的对象数组转换为对象的索引对象?

JOLT分裂和数组数据

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

如何在 Apps 脚本中循环遍历 JSON 响应

Powershell v7 文本背景突出显示

如何从字符串中创建一个逗号分隔的列表,由 API 中的 JSON 对象内的编号空格分隔?

如何在linux中用jq过滤json数组?

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

如何配置spring mvc 3在json响应中不返回null对象?

以 JSON 格式访问(新型、公共)Google 工作表

未捕获的类型错误:无法读取 null 的属性props

直接从 Java 中的模型类创建 JSON 对象

区分字符串和列表的 Pythonic 方式是什么?

如何在spark 上将json字符串转换为数据帧

JSON.stringify 向我的 Json 对象添加额外的 \ 和 "" 的问题

是否有一个 PHP 函数只在双引号而不是单引号中添加斜杠