是否可以使用带有多个JSON标签的结构? [英] Is it possible to have a struct with multiple JSON tags?
问题描述
我将请求发布到服务器并获得JSON格式的回复.我能够将其解组为一个结构.然后,我需要使用相同的数据但使用不同的JSON标签创建一个新的JSON文件.
I post a request to a server and get a reply in JSON format. I'm able to unmarshal it to a struct. Then I need to create a new JSON file with the same data but different JSON tags.
示例:
在以下代码中,我从服务器获取{"name":"Sam","age":20}
并将其解组到结构Foo
:
In the following code, I get {"name":"Sam","age":20}
from a server and unmarshal it to the struct Foo
:
type Foo struct {
Name string `json:"name"`
Age int `json:"age"`
}
然后我需要将标签name
更改为employee_name
并省略age
:
Then I need to change the tag name
to employee_name
and omit age
:
type Bar struct {
Name string `json:"employee_name"`
Age int `json:"-"`
}
之后,我将修改后的数据发送到另一台服务器.
After that I send this modified data to another server.
我知道我可以创建一个新的Bar
并将所有数据复制到其中,但是有很多字段.我想知道是否有办法像这样附加多个JSON标签:
I know I could just create a new Bar
and copy all data into it, but there are a lot of fields. I was wondering if there is a way to attach multiple JSON tags like this:
type Foo struct {
Name string `json:"name" json:"employee_name"`
Age int `json:"age" json:"-"`
}
谢谢.
推荐答案
这是不可能的. encoding/json
包仅处理struct标记中的json
键.如果json
键被多次列出(如您的示例所示),则将使用第一个(在 StructTag.Get()
).
It's not possible. The encoding/json
package only handles the json
key in struct tags. If the json
key is listed multiple times (as in your example), the first occurrence will be used (this is implemented in StructTag.Get()
).
请注意,这是encoding/json
软件包的实现限制,而不是Go的实现限制.可以轻松地创建类似的JSON编码包,该包支持多个标签键(例如json1
,json2
)或多次出现的同一键(如您的示例).
Note that this is an implementation restriction of the encoding/json
package and not that of Go. One could easily create a similar JSON encoding package supporting either multiple tag keys (e.g. json1
, json2
) or multiple occurrences of the same key (as in your example).
这篇关于是否可以使用带有多个JSON标签的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!