我在网址上返回了JSON文件:http://tvshowapi.azurewebsites.net/tvshownewsfeed
我需要能够解析json并将所有电视剧列在一个类别下。
我按照教程找到了几个解决方案但无法获取json数据并解析它。
这是我所遵循的教程的快速代码,我想同样将我的JSON文件解析为单个类别。
class AppCategory: NSObject{
var name: String?
var apps: [App]?
var type: String?
static func fetchFeaturedApps() {
let urlString = "http://www.statsallday.com/appstore/featured"
URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) ->Void in
if error != nil {
print(error)
return
}
do {
let json = try(JSONSerialization.jsonObject(with: data!, options: .mutableContainers)) as! [String: AnyObject]
var appCategories = [AppCategory]()
for dict in json["categories"] as! [[String: AnyObject]] {
let appCategory = AppCategory()
appCategory.setValuesForKeys(dict)
appCategories.append(appCategory)
}
print(appCategories)
} catch let err {
print(err)
}
}) .resume()
}
}
答案 0 :(得分:0)
下面的代码将解析json中的所有屏幕名称并将其放入一个类别。
func callApi(){
let url = NSURL(string: "http://tvshowapi.azurewebsites.net/tvshownewsfeed")
let request = NSURLRequest(url: url as! URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) { (dataRecived, response, error) in
guard error == nil else{
return
}
guard dataRecived != nil else{
return
}
do{
let jsonData = try JSONSerialization.jsonObject(with: dataRecived!, options: .mutableContainers) as! [AnyObject]
var collectScreenName = [String]()
for item in jsonData{
collectScreenName.append(item["screenName"] as! String)
}
let listOfScreen = ["category":collectScreenName]
print(listOfScreen)
}
catch let error{
print(error)
}
}
task.resume()
}