[英]Go Unmarshall json whose key can be one of 2 types
An api endpoint, not within my control, returns json with a key people that can have one of 2 types. 不在我控制范围内的api端点返回的json包含可以包含2种类型之一的关键人员。
Json: JSON:
{
"people":{
"admin":{
"Name": "John Smith",
"Address": "123 main street"
},
"user":{
"Name": "Jane Doe",
"Address": "321 broad street",
}
}
Json type 2: Json类型2:
{
"people":[
{
"name": "Jon Snow",
"pet": "Ghost"
},
{
"name": "Sansa Stark",
"pet": "Lady",
}
]
}
For the first type, I can create a structs as so 对于第一种类型,我可以这样创建一个结构
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"`
}
or the second type as 或第二种类型为
type People []*Person
type Person struct{
Name string `json:"name,omitempty"`
Pet string `json:"pet,omitempty"`
}
Is there a way to design a single struct such that I can unmarshal either type of response? 有没有一种设计单个结构的方法,使我可以解组任何一种响应?
我将people
解码到地图,然后执行断言来确定它是数组还是对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.