Golang结构的XML和JSON标签? [英] XML and JSON tags for a Golang struct?

查看:168
本文介绍了Golang结构的XML和JSON标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以根据HTTP请求标头输出为JSON或XML的应用程序。我可以通过向正在使用的结构添加正确的标签来实现正确的输出,但是我无法弄清楚如何为JSON和XML指定标签。

I have an application that can output as JSON or XML depending on the HTTP request headers. I can achieve the correct output for either by adding the correct tags to the structs I'm using, but I can't figure out how to specify the tags for both JSON and XML.

例如,这个序列化以纠正XML:

For example, this serializes to correct XML:

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

...并且这会生成正确的JSON:

...and this generates correct 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标签是空格分隔的。从手册

Go tags are space-separated. From the manual:


按照惯例,标记字符串是可选空格分隔的键:值对的连接。每个键是一个非空字符串,由空格(U + 0020'),引号(U + 0022'')和冒号(U + 003A':')之外的非控制字符组成,每个值都被引用使用U + 0022''字符和Go字符串文字语法。

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标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆