[英]Go Unmarshall json whose key can be one of 2 types
不在我控制范圍內的api端點返回的json包含可以包含2種類型之一的關鍵人員。
JSON:
{
"people":{
"admin":{
"Name": "John Smith",
"Address": "123 main street"
},
"user":{
"Name": "Jane Doe",
"Address": "321 broad street",
}
}
Json類型2:
{
"people":[
{
"name": "Jon Snow",
"pet": "Ghost"
},
{
"name": "Sansa Stark",
"pet": "Lady",
}
]
}
對於第一種類型,我可以這樣創建一個結構
type People struct {
Admin *Person `json:"admin,omitempty"`
User *Person `json:"user,omitempty"`
}
type Person struct {
Name string `json:"name,omitempty"`
Address string `json:"adress,omitempty"`
}
或第二種類型為
type People []*Person
type Person struct{
Name string `json:"name,omitempty"`
Pet string `json:"pet,omitempty"`
}
有沒有一種設計單個結構的方法,使我可以解組任何一種響應?
我將people
解碼到地圖,然后執行斷言來確定它是數組還是對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.