我尝试使用Swift从Guidebox解析JSON数据。数据的一个例子是这样的:
{
"results": [
{
"id": 14673,
"title": "The Golden Girls",
"alternate_titles": [
"Golden Palace"
],
"container_show": 0,
"first_aired": "1985-09-14",
"imdb_id": "tt0088526",
"tvdb": 71292,
"themoviedb": 1678,
"freebase": "\/m\/01fszq",
"wikipedia_id": 217200,
"tvrage": {
"tvrage_id": 5820,
"link": "http:\/\/www.tvrage.com\/shows\/id-5820"
},
"artwork_208x117": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_small\/14673-9570342022-208x117-show-thumbnail.jpg",
"artwork_304x171": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_medium\/14673-3759246217-304x171-show-thumbnail.jpg",
"artwork_448x252": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_large\/14673-2249565586-448x252-show-thumbnail.jpg",
"artwork_608x342": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_xlarge\/14673-6064109057-608x342-show-thumbnail.jpg"
}
],
"total_results": 1,
"development_api_key": "You are currently using a temporary development API key. This API key is for testing only. You have used 57 of 250 available calls. Please see the API docs (http:\/\/api.guidebox.com\/apidocs) for additional information or to generate a production API key."
}
对于我的情况,似乎使用数据的最简单方法是将其转换为[String:Any],因为我真正需要的是" id"," title&# 34;和艺术品价值。然而,我使用的所有(无数)方法都失败了,因为" alternate_titles"被解析为NSArray,它使一切变得更加困难。 到目前为止,我已经尝试过这种方法的变体:
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
let datafinal = jsonResult["results"] as! [String: Any]
//Fails around here usually, when the data is converted to [String: Any] or [Any:Any] because of the array.
let title = datafinal["title"]
} catch {
print("JSON Preocessing failed")
}
我还使用了SwiftyJSON库来尝试将数据转换为更容易阅读的JSON,但是从中提取字典的方法总是失败(我也因为结构而猜测) 。任何人都有一个简单的方法从URL获取JSON数据并轻松访问"结果"?中的值非常感谢任何帮助!
答案 0 :(得分:0)
您需要做的就是以array
访问结果,并取first element
的{{1}},array
。
将来,here是一个很好的工具,使用您可以更方便地检查数据结构的工具,它可能会更快地显示这样的问题。
Dictionary
答案 1 :(得分:0)
试试这个
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
let datafinal = jsonResult["results"] as! NSArary
let title = datafinal[0].value(forKey: "title")
print("\(title)")
} catch {
print("JSON Preocessing failed")
}