在GO语言中解析嵌套的JSON对象

huangapple go评论80阅读模式
英文:

Unmarshalling nested JSON objects in GO

问题

我将一些所有对象共有的属性合并到了一个结构体中。

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"`
}

突然间整个问题都解决了,我能够访问到所有字段。

总结一下,我无法解组我想要使用的Customer结构体。我需要重写unmarshal方法吗?我也查看了一些重写的示例,但代码非常主观。我在基类中进行的更改将导致我改变unmarshal方法。有什么干净的方法可以解决这个问题吗?

英文:

I combined some properties common to all objects into a struct.

type Document struct {
	ID        string    `json:"_id,omitempty"`
	UpdatedAt time.Time `json:"updatedat"`
	CreatedAt time.Time `json:"createdat"`
}

I also have an address struct, which is not a document.

type Address struct {
	AddressLine string `json:"addressline,omitempty"`
	City        string `json:"city,omitempty"`
	Country     string `json:"country,omitempty"`
	CityCode    int    `json:"citycode,omitempty"`
}

My customer struct is a document. It also has an address property.

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"`
}

The JSON object from MongoDB is as follows;

[
    {
        "_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
    }
]

I am using the following code to unmarshal this.

	var customerEntity Entities.Customer
	json.Unmarshal(customerEntityBytes, &customerEntity)

But all I can get is the following line. Most fields are empty.

{{ 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} {   0}   false}

As I thought this was due to the mixed nested structure, I created another customer struct for testing purposes;

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"`
}

All of a sudden the whole problem was fixed and I was able to access it with all fields filled.

In summary, I cannot unmarshal the Custumer struct I want to use. Do I need to override the unmarshall method for this? I've also reviewed the override examples but the codes are very subjective. A change I will make in base classes will cause me to change the unmarshall method. What is the clean way to this?

答案1

得分: 3

始终检查错误。

err = json.Unmarshal(customerEntityBytes, &customerEntity)
if err != nil {
    // json: 无法将数组解组为类型为Entities.Customer的Go值
}

原因是,正如@mkopriva指出的那样-你的JSON是一个数组-而你正在解组为单个结构体。要修复:

var customerEntity []Entities.Customer // 使用切片来捕获JSON数组
err = json.Unmarshal(customerEntityBytes, &customerEntity)
if err != nil { /* ... */ }

你当然可以使用自定义类型,但是通过将其嵌套在你的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

英文:

Always check errors.

err = json.Unmarshal(customerEntityBytes, &customerEntity)
if err != nil {
    // json: cannot unmarshal array into Go value of type Entities.Customer
}

and the reason is, as @mkopriva pointed out - your JSON is an array - and you are unmarshaling to a single struct. To fix:

 var customerEntity []Entities.Customer // use slice to capture JSON array
 err = json.Unmarshal(customerEntityBytes, &customerEntity)
 if err != nil { /* ... */ }

You can certainly use your custom types, but you are losing the _id tag by nesting it in your Document struct. To fix, promote it to 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"`
	
    // ...
}

Working example: https://play.golang.org/p/EMcC0d1xOLf

huangapple
  • 本文由 发表于 2021年11月7日 02:38:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/69866851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定