2016-11-22 69 views
0
对象类型解码JSON

如果您有以下JSON结构:如何基于在Golang

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

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

感谢

+0

如果有一个“类型”字段,并且所有属性都是字符串,为什么不直接解组到'[]地图[字符串]字符串'? – JimB

+0

想象一下JSON对象有许多属性,包括子对象和对象数组。 – jordan2175

回答

2

如果你想操纵你必须知道它们是什么类型的对象。 但是,如果你只是想通过他们过来,例如: 如果从数据库得到一些大的对象只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

希望这是你换货什么