2017-04-04 17 views
-4

Ich brauche für diese JSON-String zu tun, Parsen und müssen alle Werte innerhalb Iphone wie Breite zu erhalten, URL usw., irgendwelche VorschlägeJSON Parsing in Swift 3?

[[ 
    { 
    "id" : "1ab66b240b5441a35f1c963c802ebc23", 
    "sizes" : { 
     "IPhone" : { 
     "width" : 288, 
     "actualHeight" : 288, 
     "sizeName" : "IPhone", 
     "url" : "abc1.jpg", 
     "actualWidth" : 288, 
     "height" : 360 
     }, 
     "IPhone2" : { 
     "width" : 164, 
     "actualHeight" : 164, 
     "sizeName" : "Large", 
     "url" : "https:abc.jpg", 
     "actualWidth" : 164, 
     "height" : 205 
     }, 
    } 
    } 
]] 

Dank

Antwort

0

Lese JSON ist recht einfach:

{} ist Wörterbuch, [] Array ist, so dass alle verschachtelten Sammlungstypen sind Wörterbücher:

Der Einfachheit halber eine Art Alias ​​deklarieren:

typealias JSONDictionary = [String : Any] 

if let image = aObject["image"] as? JSONDictionary, 
    let sizes = image["sizes"] as? JSONDictionary, 
    let xLarge = sizes["XLarge"] as? JSONDictionary, 
    let url = xLarge["url"] as? String { 
     print(url) 
} 

PS: Nicht hässlich C-Stil Index for Schleifen in Swift basiert verwenden, ist dies die empfohlene Methode:

for aObject in arrJSON as! [JSONDictionary] { 

und löschen Sie die nächste Zeile let aObject = ....

+0

danke für die Antwort –

1

Verwendet SwiftyJSON zum Parsen der Werte und es hat gut funktioniert.

SwiftyJSON erleichtert den Umgang mit JSON-Daten in Swift. Zum Beispiel:

let json = JSON(data: dataFromNetworking) 
if let userName = json[0]["user"]["name"].string { 
    //Now you got your value 
}