ios - Swift Json data parsing without array -


i have working json data parsing array codes want change dictionary parsing. 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  array     private func getfromjson(jsondata: nsdata) throws -> [place] {         var places = [place]()         {             if let jsonarray = try nsjsonserialization.jsonobjectwithdata(jsondata, options: .allowfragments) as? [[string: anyobject]] {                 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 !

i suggest change return type of function optional:

private func getfromjson(jsondata: nsdata) throws -> place? {     var place: place?     {         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?     {         if let json = try nsjsonserialization.jsonobjectwithdata(jsondata, options: .allowfragments) as? [string: anyobject] {               place = place(properties: json)         }     } catch {         throw tmdberrors.parsingerror     }     return place } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -