首页 > 解决方案 > 在 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 方法。什么是干净的方法?

标签: gounmarshalling

解决方案


始终检查错误。

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


推荐阅读