我需要从 mongo 数据库中获取一个项目,所以我定义了一个这样的结构
type Page struct {
PageId string `bson:"pageId"`
Meta map[string]interface{} `bson:"meta"`
}
现在我还需要将其编码为 JSON,但它将字段编码为大写(我得到的是 PageId 而不是 pageId)所以我还需要为 JSON 定义字段标签。我尝试了类似的方法,但没有成功:
type Page struct {
PageId string `bson:"pageId",json:"pageId"`
Meta map[string]interface{} `bson:"meta",json:"pageId"`
}
那么如何做到这一点,在一个结构体中定义多个名称标签呢?
最佳答案
您需要做的是使用空格而不是逗号作为标签字符串分隔符。
type Page struct {
PageId string `bson:"pageId" json:"pageId"`
Meta map[string]interface{} `bson:"meta" json:"meta"`
}
它在 documentation of the reflect
package 中说:
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.
https://stackoverflow.com/questions/18635671/
相关文章:
c# - ASP.NET Core 返回带有状态码的 JSON
javascript - 通过 JavaScript 动态创建 JSON 对象(没有连接字符串)
python - json.load() 和 json.loads() 函数有什么区别
javascript - JSON.parse 意外字符错误
javascript - 如何使用 html 表单数据发送 JSON 对象
android - 如何在 Android 中使用 HTTPClient 以 JSON 格式发送 P
android - 如何在 Android 中解析 JSON?