2017-06-04 40 views
-3

我完全非常困惑與JSON在迅速工作。根據蘋果十二月 :https://developer.apple.com/swift/blog/?id=37非常困惑的工作在迅速的json

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

什麼是格式化這個jsonWithObjectRoot JSON字符串合式的方式? 我嘗試了一些方法,但成功。

所以隨後,這些方法可以訪問它。

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 
    } 
} 

回答

0

你的json看起來不錯。在投射到[String:Any]之前,您需要解析它。

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

謝謝你的回覆。我想我誤解了。所以是jsonWithObjectRoot.data .data是以json格式對jsonWithObjectRoot進行編碼的方法,並且在JSONSerialization方法將其編碼爲字典之後,我理解是否正確? – Tony

+0

沒有.data()方法從字符串轉換爲數據。數據描述了一塊內存。從Data到分析對象的轉換由JSONSerialization.jsonObject()完成。這個結果然後可以作爲一個詞典。一般來說,當你從網絡接收數據時,它的形式是一個數據類,所以你不需要進行字符串數據轉換。 – Spads

+0

再次感謝。所以進程是json-> data(jsonWithObjectRoot.data) - > dicktionary(JSONSerialization)? – Tony