go - 在 GO 中解组嵌套的 JSON 对象
问题描述
我将所有对象共有的一些属性组合到一个结构中。
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": "foo@mail.com",
"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"`
}
突然间,整个问题都解决了,我可以在填写所有字段的情况下访问它。
总之,我无法解组我想使用的客户结构。我需要为此重写 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 { /* ... */ }
您当然可以使用您的自定义类型,但是_id
通过将其嵌套在您的Document
结构中会丢失标签。要修复,请将其提升为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
推荐阅读
- geometry - 如何提取/生成与区域相交的线的交点坐标(在 fme-workbench 中)
- regex - 从字符串中排除字符不起作用
- swagger - 如何声明“列表”
' 在 OpenAPI/Swagger 文件中? - typescript - 打字稿,泛型函数可能返回回调函数
- javascript - 正则表达式中的有效格式问题
- typescript - amcharts 集成 SCRIPT1002 IE 11 中的语法错误
- php - 在 laravel 会话中使用它的键值忘记索引
- ubuntu - 如何在 Ubuntu 中模拟低磁盘写入速度?
- google-sheets - 如何在 Google Data Studio 或 Google Sheets 中将“-infinity”更改为今天的日期?
- javascript - 将函数标记为打字稿类型中的函数