SwiftDeveloper SwiftDeveloper - 3 months ago 15
iOS Question

Swift Json data parsing without array

Hello i have working json data parsing array codes but I want to change it to no array parsing. My new json file;

{
"Id": 450,
"Name": "NameforItem",
"Image": "234234.jpg"
}


My old json file working success

[{
"Id": 450,
"Name": "NameforItem",
"Image": "234234.jpg"
}]


My parsing codes.

/// Convert JSON data into array
private func getFromJSON(jsonData: NSData) throws -> [Place] {
var places = [Place]()
do {
if let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [[String: AnyObject]] {
for i in jsonArray {
var properties = [String: AnyObject]()
properties[placeJSONKeys.Id] = i[placeJSONKeys.Id]
properties[placeJSONKeys.Name] = i[placeJSONKeys.Name]
let place = Place(properties: properties)
places.append(place)
}
}
} catch {
throw TMDBErrors.ParsingError
}
return places
}


Thank you !

Answer

I suggest you to change return type of your function to Optional:

private func getFromJSON(jsonData: NSData) throws -> Place? {
    var place: Place?
    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [String: AnyObject] {
            var properties = [String: AnyObject]()
            properties[placeJSONKeys.Id] = json[placeJSONKeys.Id]
            properties[placeJSONKeys.Name] = json[placeJSONKeys.Name]
            place = Place(properties: properties)
        }
    } catch {
        throw TMDBErrors.ParsingError
    }
    return place
}

updated

 private func getFromJSON(jsonData: NSData) throws -> Place? {
    var place: Place?
    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [String: AnyObject] {


            place = Place(properties: json)
        }
    } catch {
        throw TMDBErrors.ParsingError
    }
    return place
}
Comments