我知道您可以将任意 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。
1 回答
蓝山帝景
TA贡献1843条经验 获得超7个赞
尝试使用您的 PoliticsJson 和示例 Json 字符串能够解析以获取标题和 URL。
我尝试通过将 URL 更改为 static02 并能够打印两个 URL 来为多媒体添加一个条目。
这是 PlayGround 的链接:http : //play.golang.org/p/rAJfkD1i7n
编辑
发现问题,它发生的原因是,在两个结果多媒体是字符串,即"multimedia":""
检查第 975 行和 1319 行。由于预期数组,json 失败,因为找到字符串将其转换为"multimedia":[]
.
- 1 回答
- 0 关注
- 182 浏览
添加回答
举报
0/150
提交
取消