如何在Golang中基于对象类型解码JSON

时间:2016-11-22 18:24:47

标签: json go struct stream unmarshalling

如果您有以下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
}

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

由于

1 个答案:

答案 0 :(得分:2)

如果你想操纵物体,你必须知道它们是什么类型。 但是,如果你只想传递它们,例如: 如果你从DB获得一些大对象只到它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

希望这就是你的意思