【问题标题】:How to decode JSON based on object type in Golang如何在 Golang 中根据对象类型解码 JSON
【发布时间】:2016-11-22 18:24:46
【问题描述】:

如果您有以下 JSON 结构:

[
  {
    "type": "home",
    "name": "house #1",
    ... some number of properties for home #1
  },
  {
    "type": "bike",
    "name": "trek bike #1",
    ... some number of properties for bike #1
  },
  {
    "type": "home",
    "name": "house #2",
    ... some number of properties for home #2
  }
]

在解组对象之前,如何在不知道每种类型是什么的情况下在 Golang 中将其解码为结构。看来您必须进行两次解组。

据我所知,我可能应该使用 RawMessage 来延迟解码。但我不确定这会是什么样子。

假设我有以下结构:

type HomeType struct {
  Name                  string       `json:"name,omitempty"`
  Description           string       `json:"description,omitempty"`
  Bathrooms             string       `json:"bathrooms,omitempty"`
  ... more properties that are unique to a home
}

type BikeType struct {
  Name                  string       `json:"name,omitempty"`
  Description           string       `json:"description,omitempty"`
  Tires                 string       `json:"tires,omitempty"`
  ... more properties that are unique to a bike
}

第二个问题。是否可以在流模式下执行此操作?什么时候这个数组真的很大?

谢谢

【问题讨论】:

  • 如果有一个“类型”字段,并且所有属性都是字符串,为什么不直接解组到[]map[string]string
  • 想象一下 JSON 对象有很多属性,包括子对象和对象数组。

标签: json go struct stream unmarshalling


【解决方案1】:

如果您想操作对象,您必须知道它们是什么类型。 但是,如果您只想将它​​们传递过来,例如: 如果你从数据库中得到一些大对象只到Marshal 它并将它传递给客户端, 你可以使用空的interface{} 类型:

type HomeType struct {
  Name                  interface{}        `json:"name,omitempty"`
  Description           interface{}        `json:"description,omitempty"`
  Bathrooms             interface{}        `json:"bathrooms,omitempty"`
  ... more properties that are unique to a home
}

type BikeType struct {
  Name                  interface{}        `json:"name,omitempty"`
  Description           interface{}        `json:"description,omitempty"`
  Tires                 interface{}        `json:"tires,omitempty"`
  ... more properties that are unique to a bike
}

阅读此处了解有关空接口的更多信息 - link

希望这是你的精神

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2020-11-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多