将JSON解组为结构体

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

Unmarshaling JSON into Struct

问题

我正在尝试将以下JSON字符串解组成下面的结构体:

{
   "io.confluent.connect.avro.ConnectDefault":{
      "lastModifiedAt":{
         "string":"2022-09-01T02:22:19+00:00"
      },
      "taxRateId":{
         "int":5
      },
      "basedOn":{
         "string":"Markup"
      },
      "priceTax":{
         "double":2.04
      },
      "price":{
         "int":24
      },
      "status":{
         "string":"active"
      },
      "costPrice":{
         "int":24
      },
      "createdAt":{
         "string":"2022-09-01T02:22:19+00:00"
      },
      "productId":{
         "int":3545
      },
      "ownershipId":{
         "int":1
      },
      "dbId":{
         "int":3655
      },
      "markupPercentage":{
         "int":0
      }
   }
}
type Wrapper struct {
	Message `json:"io.confluent.connect.avro.ConnectDefault"`
}

type Message struct {
	DbId Field `json:"dbId"`
}

type Field struct {
	Value map[string]interface{}
}

但是对于Field映射,它给我返回了一个空值。不确定我在这里做错了什么。

英文:

I am trying to Unmarshal the following JSON string into the struct below;

{
   "io.confluent.connect.avro.ConnectDefault":{
      "lastModifiedAt":{
         "string":"2022-09-01T02:22:19+00:00"
      },
      "taxRateId":{
         "int":5
      },
      "basedOn":{
         "string":"Markup"
      },
      "priceTax":{
         "double":2.04
      },
      "price":{
         "int":24
      },
      "status":{
         "string":"active"
      },
      "costPrice":{
         "int":24
      },
      "createdAt":{
         "string":"2022-09-01T02:22:19+00:00"
      },
      "productId":{
         "int":3545
      },
      "ownershipId":{
         "int":1
      },
      "dbId":{
         "int":3655
      },
      "markupPercentage":{
         "int":0
      }
   }
}
type Wrapper struct {
	Message `json:"io.confluent.connect.avro.ConnectDefault"`
}

type Message struct {
	DbId Field `json:"dbId"`
}

type Field struct {
	Value map[string]interface{}
}

But it gives me an empty value for the Field map. Not sure what I am doing wrong here.

答案1

得分: 4

这是因为你有额外的嵌套层级:

type Message struct {
	DbId map[string]interface{} `json:"dbId"`
}

dbId 属性的值是一个将字符串映射到任意类型的 map

英文:

It's because you have extra level of nesting:

type Message struct {
	DbId map[string]interface{} `json:"dbId"`
}

dbId property's value is a map of strings to anything.

huangapple
  • 本文由 发表于 2022年9月2日 06:21:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73575960.html
匿名

发表评论

匿名网友

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

确定