json 如何在结构中定义多个名称标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18635671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define multiple name tags in a struct
提问by Sofia
I need to get an item from a mongo database, so I defined a struct like this
我需要从 mongo 数据库中获取一个项目,所以我定义了一个这样的结构
type Page struct {
PageId string `bson:"pageId"`
Meta map[string]interface{} `bson:"meta"`
}
Now I also need to encode it to JSON, but it encodes the fields as uppercase (i get PageId instead of pageId) so i also need to define field tags for JSON. I tried something like this but it didn't work:
现在我还需要将它编码为 JSON,但它将字段编码为大写(我得到的是 PageId 而不是 pageId),所以我还需要为 JSON 定义字段标签。我试过这样的事情,但没有奏效:
type Page struct {
PageId string `bson:"pageId",json:"pageId"`
Meta map[string]interface{} `bson:"meta",json:"pageId"`
}
So how can this be done, define multiple name tags in a struct?
那么如何做到这一点,在结构中定义多个名称标签?
回答by ANisus
It says in the documentation of the reflectpackage:
它在reflect包的文档中说:
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.
按照惯例,标签字符串是可选的空格分隔键:“值”对的串联。每个键都是一个非空字符串,由除空格 (U+0020 ' ')、引号 (U+0022 '"') 和冒号 (U+003A ':') 以外的非控制字符组成。每个值都被引用使用 U+0022 '"' 字符和 Go 字符串文字语法。
What you need to do is to use space instead of comma as tag string separator.
您需要做的是使用空格而不是逗号作为标记字符串分隔符。
type Page struct {
PageId string `bson:"pageId" json:"pageId"`
Meta map[string]interface{} `bson:"meta" json:"meta"`
}
回答by Benny
Thanks for the accepted answer.
感谢您接受的答案。
Below is just for the lazy people like me.
下面只针对我这种懒人。
INCORRECT
不正确
type Page struct {
PageId string `bson:"pageId",json:"pageId"`
Meta map[string]interface{} `bson:"meta",json:"pageId"`
}
CORRECT
正确的
type Page struct {
PageId string `bson:"pageId" json:"pageId"`
Meta map[string]interface{} `bson:"meta" json:"pageId"`
}

