如何在Swift 3中使用循环打印JSON值? [英] How to print JSON values using a loop in Swift 3?
本文介绍了如何在Swift 3中使用循环打印JSON值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了这个JSON:
{
cover = {
id = 1;
};
description = "Test"
place = {
id = 11;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
},
{
cover = {
id = 2;
};
description = "Cool"
place = {
id = 22;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
}
这是我的代码:
if let fbData = result as? [String : Any] {
print(fbData)
for events in fbData {
print (events["name"] as! String)
//this displays an error
//Type (Key: String, value: Any) has subscript members
}
}
但是我不知道如何遍历它们
我已经尝试过这些解决方案,但是它们从未起作用:
解决方案
if let array = result as? [String : AnyObject]{
if let fbData = array["data"] as? [[String : AnyObject]] {
print(fbData)
for event in fbData {
print (event["name"] as! String)
}
}
}
-
result
是Any
类型 - 将其发布到字典中-
[String : AnyObject]
- 提取
data
并转换为字典数组-[[String : AnyObject]]
.
I got this JSON:
{
cover = {
id = 1;
};
description = "Test"
place = {
id = 11;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
},
{
cover = {
id = 2;
};
description = "Cool"
place = {
id = 22;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
}
This is my code:
if let fbData = result as? [String : Any] {
print(fbData)
for events in fbData {
print (events["name"] as! String)
//this displays an error
//Type (Key: String, value: Any) has subscript members
}
}
But I don't know how to loop through them
I already tried these solutions but they never worked:
Correctly Parsing JSON in Swift 3
解决方案
if let array = result as? [String : AnyObject]{
if let fbData = array["data"] as? [[String : AnyObject]] {
print(fbData)
for event in fbData {
print (event["name"] as! String)
}
}
}
result
is ofAny
type- Cast it into Dictionary -
[String : AnyObject]
- Extract
data
and cast to Array of Dictionaries -[[String : AnyObject]]
.
这篇关于如何在Swift 3中使用循环打印JSON值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文