2017-01-02 76 views
2

我想使用Alamofire將JSON數據轉換爲Swift中的Dictionary。 我正在嘗試if let dict = response.result.value as? Dictionary<String, AnyObject> { ... },不幸的是它不起作用。有什麼建議麼?提前致謝。這是例如打印我response.result.value使用Alamofire將JSON轉換爲Swift中的字典

Optional(<__NSArrayI 0x6000002893d0>(
{ 
    category = category1; 
    description = description1; 
    name = sth1; 
    id = 1; 
    price = "213"; 
    type = type1; 
}, 
{ 
    category = category2; 
    description = description2; 
    name = sth2; 
    id = 2; 
    price = "2133"; 
    type = type4; 
}, 
{ 
    category = category3; 
    description = description3; 
    name = sth3; 
    id = 3; 
    price = "21334"; 
    type = type5; 
} 
) 
) 
+0

爲什麼不使用[ObjectMapper](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwipqdDNzqPRAhWPN1AKHeXAA7wQFggbMAA&url=https%3A%2F %2Fgithub.com%2FHearst-DD%2FObjectMapper&usg = AFQjCNFyUn25wAdc4YI3J79e10bh5EsWTQ)? –

回答

1

您需要從您的JSON步步... 提取數據,你可以不喜歡這樣。

if let arrayOfDic = response.result.value as? [Dictionary<String,AnyObject>]{ 
     for aDic in arrayOfDic{ 
      print(aDic)//print each of the dictionaries 
      if let price = aDic["price"] as? String{ 
       print(price)//print price of each dic 
      } 
     } 
    } 
3

因爲你的反應是一個數組,所以你需要創建一個字典的數組。只有字典不會從你的上述迴應中起作用。 因此,改變下面的代碼。

if let dict = response.result.value as? [[String : AnyObject]] 
{ ... } 
相關問題