加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang结构的XML和JSON标签?

发布时间:2020-12-16 19:20:21 所属栏目:大数据 来源:网络整理
导读:我有一个可以根据HTTP请求标头输出为JSON或XML的应用程序。我可以通过向正在使用的结构添加正确的标签来实现正确的输出,但是我无法确定如何为JSON和XML指定标签。 例如,这是序列化以纠正XML: type Foo struct { Id int64 `xml:"id,attr"` Version int16 `
我有一个可以根据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,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"`
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读