我知道您可以将任意 JSON 解组为map[string]interface{}value,虽然这有效,但我的 JSON 响应始终是定义和一致的,为了简单起见,我更愿意将其解组为嵌套结构。
这是 JSON 响应的示例,缩写为:
{
(...)
"results": [
{
"section": "N.Y. / Region",
"subsection": "",
"title": "Christie Spins His Version of Security Record on Trail",
"abstract": "An examination of Gov. Chris Christie’s record as New Jersey’s top federal prosecutor shows that he has, at times, overstated the significance of the terrorism prosecutions he oversaw.",
"url": "http://www.nytimes.com/2015/12/27/nyregion/Christie-markets-himself-as-protector-to-gain-in-polls.html",
"byline": "By ALEXANDER BURNS and CHARLIE SAVAGE",
"item_type": "Article",
"updated_date": "2015-12-26T18:04:19-5:00",
(...)
"multimedia": [
{
"url": "http://static01.nyt.com/images/2015/12/27/nyregion/27CHRISTIE1/27CHRISTIE1-thumbStandard.jpg",
"format": "Standard Thumbnail",
"height": 75,
"width": 75,
"type": "image",
"subtype": "photo",
"caption": "Gov. Chris Christie of New Jersey spoke about the Sept. 11, 2001, attacks at a Republican conference last month.",
"copyright": "Stephen Crowley/The New York Times"
}
(...)
]
}
]
}
我基本上只想打印出多媒体数组中最后一个对象的标题和 URL。(我只是想让它工作,所以请原谅错误处理。)
这是我得到的错误: panic: json: cannot unmarshal string into Go value of type []struct { URL string "json:\"url\"" }
问题Multimedia显然出在结构上。让我感到困惑的是,这个错误似乎表明它被解释为一个字符串,但我将结构更改为这个以确保:
type PoliticsJson struct {
Results []struct {
Multimedia string `json:"multimedia"`
Title string `json:"title"`
} `json:"results"`
}
而且我得到了panic: json: cannot unmarshal array into Go value of type string,这表明它是被解释为JSON的数组。
同样,我基本上只想打印出多媒体数组中最后一个对象的标题和 URL。
蓝山帝景
相关分类