[英]Unmarshal only gives me first element of array that is nested in JSON response
我正在尝试使用Flickr API,并且有一个端点可以给我这样的响应
{
"photos": {
"page": 1,
"pages": 500,
"perpage": 1,
"total": 500,
"photo": [
{
"id": "12345",
"owner": "12345@N01",
"secret": "12ab345xyz",
"server": "1234",
"farm": 1,
"title": "Some Title",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
...
]
},
"stat": "ok"
}
我有一个看起来像这样的结构
type FlickrResp struct {
Photos struct {
Page int `json:"page"` //what page the results were retreived from
Pages int `json:"pages"` //total number of pages of results
Perpage int `json:"perpage"` //number of results per page
Total int `json:"total"` //total number of results
Photo []struct {
ID string `json:"id"` //image ID
Owner string `json:"owner"` //owner ID
Secret string `json:"secret"` //owner secret
Server string `json:"server"` //server ID
Farm int `json:"farm"` //farm ID
Title string `json:"title"` //image title
Ispublic string `json:"ispublic"` //is image publicly viewable?
Isfriend string `json:"isfriend"` //is image owner my friend?
Isfamily string `json:"isfamily"` //is image owner my family?
} `json:"photo"` //array of objects with details of photos
} `json:"photos"` //object that holds information about photoset
Stat string `json:"stat"` //status
}
我正试图解组
var fr FlickrResp //create blank struct of type FlickrResp to hold JSON
resp, err := ioutil.ReadAll(flickrCB.Body) //read HTTP GET response
if err != nil {
}
json.Unmarshal([]byte(resp), &fr) //serialize JSON into template
flickCB.Body来自http.Get
问题是我只得到照片阵列的第一个元素。 当我将响应对象转换为字符串打印时,可以看到有多个元素。 我究竟做错了什么? 几天来,我一直在反对Unmarshal和更复杂的JSON响应。
最初在评论中回答,但有一点澄清:
json.Unmarshal
有一个未捕获的错误:
json: cannot unmarshal number into Go value of type string
由闪烁API提供整数形式的ispublic
, isfriend
和isfamily
API之间的类型不匹配引起,但该结构期望字符串。 一个简单的解决方法是将它们转换为整数。
这些情况的另一种选择是使用json.Number
,它包装了源json中的基本字符串,并提供了一些方便的方法来稍后将其转换为数字(或只是将其保留为字符串)。 通过说
Ispublic json.Number `json:"ispublic"` //is image publicly viewable?
Isfriend json.Number `json:"isfriend"` //is image owner my friend?
Isfamily json.Number `json:"isfamily"`
它将正常工作,并且可以通过fr.Ispublic.String()
轻松将结果作为字符串fr.Ispublic.String()
。
在这种情况下可能更有用的更精细的更改是使用自定义布尔类型。 有问题的值似乎反映了布尔值,但是整数也不能干净地映射到布尔值。 可以使用自定义反序列化类型。 从此示例借用stackoverflow的其他地方:
type ConvertibleBoolean bool
func (bit ConvertibleBoolean) UnmarshalJSON(data []byte) error {
asString := string(data)
if asString == "1" || asString == "true" {
bit = true
} else if asString == "0" || asString == "false" {
bit = false
} else {
return errors.New(fmt.Sprintf("Boolean unmarshal error: invalid input %s", asString))
}
return nil
}
上面的代码使您可以将Is*
值声明为ConvertibleBoolean
,并将自动将在Flickr到布尔值的那些字段中获得的0和1值自动映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.