GO 语言中处理嵌套 JSON 对象
时间:2024-02-27
浏览:231
作者:佚名
大家好,我们又见面了啊~本文《GO 语言中处理嵌套 JSON 对象》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
我将所有对象共有的一些属性组合到一个结构中。
type document struct {
id string `json:"_id,omitempty"`
updatedat time.time `json:"updatedat"`
createdat time.time `json:"createdat"`
}
我还有一个地址结构,它不是文档。
type address struct {
addressline string `json:"addressline,omitempty"`
city string `json:"city,omitempty"`
country string `json:"country,omitempty"`
citycode int `json:"citycode,omitempty"`
}
我的客户结构是一个文档。它还有一个地址属性。
type customer struct {
document `json:"document"`
address address `json:"address"`
name string `json:"name,omitempty"`
email string `json:"email,omitempty"`
valid bool `json:"valid,omitempty"`
}
来自 mongodb 的 json 对象如下;
[
{
"_id": "6186b4556971a9dbae117333",
"address": {
"addressline": "foo address",
"city": "foo city",
"citycode": 0,
"country": "foo country"
},
"document": {
"createdat": "0001-01-01t03:00:00+03:00",
"updatedat": "0001-01-01t03:00:00+03:00"
},
"email": "[email protected]",
"name": "foo fooster",
"valid": false
}
]
我正在使用以下代码来解组它。
var customerentity entities.customer
json.unmarshal(customerentitybytes, &customerentity)
但我所能得到的只是下面这行。大多数字段都是空的。
{{ 0001-01-01 00:00:00 +0000 utc 0001-01-01 00:00:00 +0000 utc} { 0} false}
由于我认为这是由于混合嵌套结构造成的,因此我创建了另一个客户结构用于测试目的;
import "time"
type AutoGenerated []struct {
ID string `json:"_id"`
Address struct {
Addressline string `json:"addressline"`
City string `json:"city"`
Citycode int `json:"citycode"`
Country string `json:"country"`
} `json:"address"`
Document struct {
Createdat time.Time `json:"createdat"`
Updatedat time.Time `json:"updatedat"`
} `json:"document"`
Email string `json:"email"`
Name string `json:"name"`
Valid bool `json:"valid"`
}
突然之间,整个问题得到了解决,我能够在填充所有字段的情况下访问它。
总之,我无法解组我想要使用的 custumer 结构。我是否需要为此重写 unmarshall 方法?我还查看了覆盖示例,但代码非常主观。我将在基类中进行的更改将导致我更改 unmarshall 方法。干净的方法是什么?
正确答案
始终检查错误。
err = json.unmarshal(customerentitybytes, &customerentity)
if err != nil {
// json: cannot unmarshal array into go value of type entities.customer
}
原因是,正如 @mkopriva 指出的那样 - 你的 json 是一个数组 - 并且你正在解组到单个结构。修复:
var customerentity []entities.customer // use slice to capture json array
err = json.unmarshal(customerentitybytes, &customerentity)
if err != nil { /* ... */ }
您当然可以使用自定义类型,但是通过将 document 结构嵌套在 document 结构中,您会丢失 _id 标记。要修复此问题,请将其升级为 customer:
type Document struct {
//ID string `json:"_id,omitempty"`
UpdatedAt time.Time `json:"updatedat"`
CreatedAt time.Time `json:"createdat"`
}
type Customer struct {
ID string `json:"_id,omitempty"`
// ...
}
工作示例:https://play.golang.org/p/EMcC0d1xOLf
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《GO 语言中处理嵌套 JSON 对象》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
