假设我有一个JSON消息,看起来像这样:
{
"type": string
"data": list of something that is based on above type
}
两个例子可能是
{
"type": "car"
"data": [{"color": "red", "mpg": 16.4}]
}
和
{
"type": "house"
"data": [{"color": "blue", "state": "CA"}]
}
I want to define a struct so I can basically only decode the type 和 then use that to properly unmarshal the data field. I tried the following
type message struct {
Type string `json:"type"`
Data []byte `json:"data"`
}
type car struct {
Color string
MPG float64
}
type house struct {
Color string
State string
}
erroneously thinking that it would just leave the Data field raw for me to unmarshal later into either the car
or house
struct. I know I can define Data as a []interface{}
和 do some other work to get what I want, but I was wondering if this is (currently) the best way in Go? In case it comes up, assume I cannot change the JSON definitions - I'm just the consumer of a service here.