解析具有动态Key的对象(Parse a JSON object with dynamic key)
下面再做一下复杂的变通,如果把上面的对象数组变为Key为水果ID的对象(object of object)比如
"Fruit" : {
"1": {
"Name": "Apple",
"PriceTag": "$1"
},
"2": {
"Name": "Pear",
"PriceTag": "$1.5"
}
}
每个Key的名字在声明结构体的时候是不知道值的,这样该怎么声明呢,答案是把Fruit字段的类型声明为一个key为string类型值为Fruit类型的map
package main
import (
"encoding/json"
"fmt"
"time"
)
func main() {
type Fruit struct {
Name string `json:"Name"`
PriceTag string `json:"PriceTag"`
}
type FruitBasket struct {
Name string
Fruit map[string]Fruit
Id int64 `json:"ref"`// 声明对应的json key
Created time.Time
}
jsonData := []byte(`
{
"Name": "Standard",
"Fruit" : {
"1": {
"Name": "Apple",
"PriceTag": "$1"
},
"2": {
"Name": "Pear",
"PriceTag": "$1.5"
}
},
"ref": 999,
"Created": "2018-04-09T23:00:00Z"
}`)
var basket FruitBasket
err := json.Unmarshal(jsonData, &basket)
if err != nil {
fmt.Println(err)
}
for _, item := range basket.Fruit {
fmt.Println(item.Name, item.PriceTag)
}
}