我有json之类的
{
"api_type" : "abc",
"api_name" : "xyz",
"cities" : {
"new_york" : {
"lat":"40.730610",
"long":"-73.935242"
},
"london" : {
"lat":"51.508530",
"long":"-0.076132"
},
"amsterdam" : {
"lat":"52.379189",
"long":"4.899431"
}
//cities can be multiple
}
}
我可以使用以下结构来解码
type MyJsonName struct {
APIName string `json:"api_name"`
APIType string `json:"api_type"`
Locations struct {
Amsterdam struct {
Lat string `json:"lat"`
Long string `json:"long"`
} `json:"amsterdam"`
London struct {
Lat string `json:"lat"`
Long string `json:"long"`
} `json:"london"`
NewYork struct {
Lat string `json:"lat"`
Long string `json:"long"`
} `json:"new_york"`
} `json:"locations"`
}
但是我的城市名称和号码在每个响应中都会有所不同,这是解码这种类型的json的最佳方法,其中键可以是字符串,且字符串会有所不同。
最佳答案
我将locations
制成 map (尽管您在JSON中将其称为cities
):
type MyJsonName struct {
APIName string `json:"api_name"`
APIType string `json:"api_type"`
Locations map[string]struct {
Lat string
Long string
} `json:"locations"`
}
关于json - Golang : best way to unmarshal following json with string as keys,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36299867/