2017-06-04 7 views
-3

Ich bekomme völlig verwirrt mit JSON in Swift arbeiten. laut Apple Dezember: https://developer.apple.com/swift/blog/?id=37sehr verwirrt arbeiten auf JSON in Swift

/* 
    { 
     "someKey": 42.0, 
     "anotherKey": { 
     "someNestedKey": true 
     } 
    } 
*/ 

Was für eine gut gebildete Art und Weise dieser Zeichenfolge jsonWithObjectRoot json zu formatieren? Ich versuchte Serval Wege aber n Erfolg.

so können diese Methoden anschließend darauf zugreifen.

if let dictionary = jsonWithObjectRoot as? [String: Any] { 
    if let number = dictionary["someKey"] as? Double { 
     // access individual value in dictionary 
    } 

    for (key, value) in dictionary { 
     // access all key/value pairs in dictionary 
    } 

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]  { 
     // access nested dictionary values by key 
    } 
} 

Antwort

0

Ihr JSON sieht gut aus. Sie müssen es analysieren, bevor Sie zu [String: Any] umwandeln.

let jsonWithObjectRoot = "{ \"someKey\": 42.0, \"anotherKey\": { \"someNestedKey\": true } }" 
let data = jsonWithObjectRoot.data(using:.utf8)! 
do { 
    let json = try JSONSerialization.jsonObject(with:data) 
    if let dictionary = json as? [String: Any] { 
     if let number = dictionary["someKey"] as? Double { 
      // access individual value in dictionary 
     } 

     for (key, value) in dictionary { 
      // access all key/value pairs in dictionary 
     } 

     if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]  
     { 
      // access nested dictionary values by key 
     } 
    } 
} catch { 
    print("Error parsing Json") 
} 
+0

Vielen Dank für die Antworten. Ich glaube, ich habe es falsch verstanden. Also ist jsonWithObjectRoot.data die .data ist die Methode, um jsonWithObjectRoot im JSON-Format zu kodieren und nach der JSONSerialization-Methode kodiert es ins Dictionary, habe ich das richtig verstanden? – Tony

+0

Keine .data() - Methode konvertiert von String in Daten. Daten beschreiben einen Speicherblock. Die Konvertierung von Data in das analysierte Objekt erfolgt über JSONSerialization.jsonObject(). Das Ergebnis kann dann als Dictionary umgewandelt werden. Wenn Sie Daten aus dem Internet erhalten, liegt dies in der Regel in Form einer Data-Klasse vor, sodass Sie die String Data-Konvertierung nicht durchführen müssen. – Spads

+0

Danke nochmal. Also sind die Prozesse json-> data (jsonWithObjectRoot.data) -> dicktionary (JSONSerialization)? – Tony

Verwandte Themen