我正在使用以下代码来序列化来自Web服务器的json响应,并尝试获取所有键值对。
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 = 0123456789012;
"category_id" = 57022;
"primary_desc" = "MK25T/S600T Regulator combo ";
stock = 0;
"store_id" = 49537;
}]
我的响应有很多嵌套数组,因为“Part”是嵌套数组之一,我想打印它的所有键值对。这里当我打印resultJson时,我可以看到我的整个回复。我跟着https://developer.apple.com/swift/blog/?id=37。有人可以帮我修复这段代码。提前谢谢。
答案 0 :(得分:2)
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)")
}