2015-08-24 42 views
1

API返回下面的響應,但我不知道如何解析它。如何從複雜的字典中獲取價值?

響應JSON

[ 
"results": [ 
    [ 
     "address": "mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3", 
     "total": [ 
     "balance": 0, 
     "received": 0, 
     "sent": 0 
     ], 
     "confirmed": [ 
     "balance": 0, 
     "received": 0, 
     "sent": 0 
     ] 
    ] 
    ] 
] 

Swift代碼

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
appDelegate.chain!.getAddress(address!) { dictionary, error in 
    NSLog("%@", dictionary) 
} 

Dictionary對象

(lldb) po dictionary 
[results: (
     { 
     address = mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3; 
     confirmed =   { 
      balance = 0; 
      received = 0; 
      sent = 0; 
     }; 
     total =   { 
      balance = 0; 
      received = 0; 
      sent = 0; 
     }; 
    } 
)] 

我嘗試了很多次......你能不能分享一下如何解決這個問題,請..

(lldb) po dictionary["results"]![0] 
{ 
    address = mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3; 
    confirmed =  { 
     balance = 0; 
     received = 0; 
     sent = 0; 
    }; 
    total =  { 
     balance = 0; 
     received = 0; 
     sent = 0; 
    }; 
} 

po dictionary["results"]![0]!["address"] 
error: <EXPR>:1:28: error: cannot subscript a value of type 'AnyObject' with an index of type 'String' 
dictionary["results"]![0]!["address"] 

我在「let address = ...」行有「找不到成員'下標'」。

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.chain!.getAddress(address!) { dictionary, error in 
     NSLog("%@", dictionary) 

     let address = dictionary["results"]![0]["address"]! 
     print("address: \(address)") 
    } 
+1

訪問容器內容不解析。 JSON是文本,將其轉換爲集合對象的過程就是解析。 – zaph

+1

由於我的回答不回答我刪除它的問題。 – zaph

+1

你是在唱Swift 1.2還是在用Swift 2開發?我問這是因爲它在Swift 2中使用'guard'語句解析它有點整潔 –

回答

0
if let myDictionary = dictionary as? [String:AnyObject] { 
if let results = myDictionary["results"] as? [AnyObject] { 
    if let firstItem = results[0] as? [String: AnyObject] { 
     if let address = firstItem["address"] as? String { 
      print(address) 
     } 
     if let total = firstItem["total"] as? [String:Int] { 
      if let balance = total["balance"] { 
       print(balance) 
      } 
      if let received = total["received"] { 
       print(received) 
      } 
      if let sent = total["sent"] { 
       print(sent) 
      } 
     } 
     if let confirmed = firstItem["confirmed"] as? [String:Int] { 
      if let balance = confirmed["balance"] { 
       print(balance) 
      } 
      if let received = confirmed["received"] { 
       print(received) 
      } 
      if let sent = confirmed["sent"] { 
       print(sent) 
      } 
     } 
    } 
} 
} 

爲了簡化事情,你可以創建一個類,如果返回的數據將被處理這樣的分析總是具有相同的格式。

+0

它的工作!非常感謝! – zono

+0

@zono歡迎您。在Swift 2中,使用守護關鍵字可以更輕鬆地完成此操作。因此,如果您計劃在幾周內發佈,我強烈建議您遷移;) –

+0

好的,我會切換到Swift2。 – zono