2017-01-02 17 views
2

Alamofireを使用してJSONデータをSwiftのDictionaryに変換したいと思います。 私はif let dict = response.result.value as? Dictionary<String, AnyObject> { ... }を試していましたが、残念ながらそれは動作しません。助言がありますか?前もって感謝します。これは、辞書の配列を作成する必要がありますので、あなたの応答が配列であるので、私のresponse.result.valueAlamofireを使用してSwiftでJSONを辞書に変換する

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]] 
{ ... } 
関連する問題