SwiftDeveloper SwiftDeveloper - 4 months ago 38
JSON Question

Swift json delete key

I want to parsing my json file without "results" tab my new json file

[
{
"Id": 708,
"Name": "My name",
"ImageUrl": "2016728135316.jpg"
}


Codes under below

private func getMoviesFromJSON(jsonData: NSData) throws -> [Movie] {
var movies = [Movie]()
do {
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [String: AnyObject], jsonArray = jsonObject["results"] as? [[String: AnyObject]] {
for i in jsonArray {
var properties = [String: AnyObject]()
properties[JSONKeys.id] = i[JSONKeys.id]
properties[JSONKeys.title] = i[JSONKeys.title]
properties[JSONKeys.posterPath] = i[JSONKeys.posterPath]
let movie = Movie(properties: properties)
movies.append(movie)
}
}
} catch {
throw TMDBErrors.ParsingError
}
return movies
}


I think must be change this line or must be delete.


jsonObject["results"]


I need your help , Thank You !

Answer

Your json doesn't have any results parameter .. so you don't need it at all ..

     do {
        if let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [[String: AnyObject]] {
            for i in jsonArray {
                var properties = [String: AnyObject]()
                properties[JSONKeys.id] = i[JSONKeys.id]
                properties[JSONKeys.title] = i[JSONKeys.title]
                properties[JSONKeys.posterPath] = i[JSONKeys.posterPath]
                let movie = Movie(properties: properties)
                movies.append(movie)
            }
        }
    } catch {
        throw TMDBErrors.ParsingError
    }
Comments