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

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

Unmarshalling nested JSON objects in GO

问题

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

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

我还有一个地址结构体,它不是一个文档。

  1. type Address struct {
  2. AddressLine string `json:"addressline,omitempty"`
  3. City string `json:"city,omitempty"`
  4. Country string `json:"country,omitempty"`
  5. CityCode int `json:"citycode,omitempty"`
  6. }

我的客户结构体是一个文档。它还有一个地址属性。

  1. type Customer struct {
  2. Document `json:"document"`
  3. Address Address `json:"address"`
  4. Name string `json:"name,omitempty"`
  5. Email string `json:"email,omitempty"`
  6. Valid bool `json:"valid,omitempty"`
  7. }

来自MongoDB的JSON对象如下所示:

  1. [
  2. {
  3. "_id": "6186b4556971a9dbae117333",
  4. "address": {
  5. "addressline": "Foo Address",
  6. "city": "Foo City",
  7. "citycode": 0,
  8. "country": "Foo Country"
  9. },
  10. "document": {
  11. "createdat": "0001-01-01T03:00:00+03:00",
  12. "updatedat": "0001-01-01T03:00:00+03:00"
  13. },
  14. "email": "foo@mail.com",
  15. "name": "Foo Fooster",
  16. "valid": false
  17. }
  18. ]

我正在使用以下代码进行解组:

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

但是我只能得到以下一行。大多数字段都是空的。

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

我认为这是由于混合的嵌套结构导致的,所以我为测试目的创建了另一个客户结构体;

  1. import "time"
  2. type AutoGenerated []struct {
  3. ID string `json:"_id"`
  4. Address struct {
  5. Addressline string `json:"addressline"`
  6. City string `json:"city"`
  7. Citycode int `json:"citycode"`
  8. Country string `json:"country"`
  9. } `json:"address"`
  10. Document struct {
  11. Createdat time.Time `json:"createdat"`
  12. Updatedat time.Time `json:"updatedat"`
  13. } `json:"document"`
  14. Email string `json:"email"`
  15. Name string `json:"name"`
  16. Valid bool `json:"valid"`
  17. }

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

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

英文:

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

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

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

  1. type Address struct {
  2. AddressLine string `json:"addressline,omitempty"`
  3. City string `json:"city,omitempty"`
  4. Country string `json:"country,omitempty"`
  5. CityCode int `json:"citycode,omitempty"`
  6. }

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

  1. type Customer struct {
  2. Document `json:"document"`
  3. Address Address `json:"address"`
  4. Name string `json:"name,omitempty"`
  5. Email string `json:"email,omitempty"`
  6. Valid bool `json:"valid,omitempty"`
  7. }

The JSON object from MongoDB is as follows;

  1. [
  2. {
  3. "_id": "6186b4556971a9dbae117333",
  4. "address": {
  5. "addressline": "Foo Address",
  6. "city": "Foo City",
  7. "citycode": 0,
  8. "country": "Foo Country"
  9. },
  10. "document": {
  11. "createdat": "0001-01-01T03:00:00+03:00",
  12. "updatedat": "0001-01-01T03:00:00+03:00"
  13. },
  14. "email": "foo@mail.com",
  15. "name": "Foo Fooster",
  16. "valid": false
  17. }
  18. ]

I am using the following code to unmarshal this.

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

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

  1. {{ 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;

  1. import "time"
  2. type AutoGenerated []struct {
  3. ID string `json:"_id"`
  4. Address struct {
  5. Addressline string `json:"addressline"`
  6. City string `json:"city"`
  7. Citycode int `json:"citycode"`
  8. Country string `json:"country"`
  9. } `json:"address"`
  10. Document struct {
  11. Createdat time.Time `json:"createdat"`
  12. Updatedat time.Time `json:"updatedat"`
  13. } `json:"document"`
  14. Email string `json:"email"`
  15. Name string `json:"name"`
  16. Valid bool `json:"valid"`
  17. }

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

始终检查错误。

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

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

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

你当然可以使用自定义类型,但是通过将其嵌套在你的Document结构体中,你会丢失_id标签。要修复,将其提升到Customer中:

  1. type Document struct {
  2. //ID string `json:"_id,omitempty"`
  3. UpdatedAt time.Time `json:"updatedat"`
  4. CreatedAt time.Time `json:"createdat"`
  5. }
  6. type Customer struct {
  7. ID string `json:"_id,omitempty"`
  8. // ...
  9. }

工作示例:https://play.golang.org/p/EMcC0d1xOLf

英文:

Always check errors.

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

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

  1. var customerEntity []Entities.Customer // use slice to capture JSON array
  2. err = json.Unmarshal(customerEntityBytes, &customerEntity)
  3. 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:

  1. type Document struct {
  2. //ID string `json:"_id,omitempty"`
  3. UpdatedAt time.Time `json:"updatedat"`
  4. CreatedAt time.Time `json:"createdat"`
  5. }
  6. type Customer struct {
  7. ID string `json:"_id,omitempty"`
  8. // ...
  9. }

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:

确定