2017-06-21 9 views
1

次のコードを使用してWebサーバーからjson応答をシリアル化し、すべてのキー値のペアを取得しようとしています。サーバーからswiftのキーに基づいた値を取得3

do { 
    let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] 

    if let dictionary = resultJson as? [String: Any] { 
     if let nestedDictionary = dictionary["Part"] as? [String: Any] { 
      // access nested dictionary values by key 
      for (key, value) in dictionary { 
       // access all key/value pairs in dictionary 
       print(key) 
       print(value) 
      } 
     } 
    } 
} catch { 
     print("Error -> \(error)") 
} 

私の応答は

["ProductInfo": { 

}, "PartTax": <__NSCFArray 0x166cff60>(
{ 

}, 
{ 

}, 
{ 

} 
) 
, "PartLog": <__NSCFArray 0x166d0a70>(
{ 

}, 
{ 

}, 
{ 

}, 
{ 

} 
) 
, "ReceivedItem": { 

}, "PartPriceLevel": <__NSCFArray 0x166cfd50>(
{ 

}, 
{ 

}, 
{ 

}, 
{ 

}, 
{ 

}, 

{ 

}, 
{ 

}, 
{ 

} 
) 
, "Part": { 
    "auxiliary_desc" = "Connie's keyman"; 
    barcode =; 
    "category_id" = 57022; 
    "primary_desc" = "MK25T/S600T Regulator combo "; 
    stock = 0; 
    "store_id" = 49537; 
}] 

私の応答は、「パート」でネストされた配列をたくさん持っているされてネストされた配列の一つであり、私はそのキーと値のペアのすべてを印刷したいです。ここでresultJsonを印刷すると、私の全回答を見ることができます。私はhttps://developer.apple.com/swift/blog/?id=37に続きます。このコードを修正するのに役立つ人がいますか?前もって感謝します。

+0

理解を深めるために「JSON」を共有できますか? –

+1

あなたが使用する必要があるのは、 'jsonWithObjectRoot'のところに' resultJson'です。 –

+0

あなたは私の答えを試してみませんか?答えは 'resultJson'です。 –

答えて

1
do { 
    let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] 

    if let dictionary = resultJson as? [String: Any] { 
     if let nestedDictionary = dictionary["Part"] as? [String: Any] { 
      // access nested dictionary values by key 
      for (key, value) in nestedDictionary { 
       // access all key/value pairs in dictionary 
       print(key) 
       print(value) 
      } 
     } 
    } 
} catch { 
    print("Error -> \(error)") 
} 
+0

をもう一度編集しました全体の応答を表示 –

+0

更新された応答を確認する、forループで 'nestedDictionary'を使用するのを忘れました –

+1

ありがとうございました。 –

関連する問題