我有一个HTTP请求,响应如下:
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "carter",
"last": "roy"
},
"location": {
"street": "8662 pine rd",
"city": "minto",
"state": "nova scotia",
"postcode": "I8Q 4L3",
"coordinates": {
"latitude": "-65.0674",
"longitude": "-174.1034"
},
"timezone": {
"offset": "+8:00",
"description": "Beijing, Perth, Singapore, Hong Kong"
}
},
"email": "carter.roy@example.com",
"login": {...},
"dob": {
"date": "1972-07-18T03:10:43Z",
"age": 46
},
"registered": {
"date": "2014-05-14T07:12:34Z",
"age": 5
},
"phone": "174-802-7804",
"cell": "194-903-4287",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/9.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/9.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/9.jpg"
},
"nat": "CA"
}
],
"info": {...}
}
每次刷新页面时,响应始终会改变。
问题是,某些字段(例如邮政编码)将是字符串或整数,因此如何为“邮政编码”这样的字段指定多种类型:
type Location struct {
Street string `json:"street"`
Postcode string `json:"postcode"`
Coordinates Coordinates `json:"coordinates"`
}
这不是重复项,因为在我的情况下,我为字段具有两种不同的数据类型(即,字符串和int表示邮政编码),因此如何在结构中指定它。我不鼓励循环访问原始数据以进行类型检查。