如何在Swift 3中使用循环打印JSON值?

时间:2016-09-14 07:52:31

标签: json swift

我得到了这个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
}

}

但我不知道如何循环使用它们

我已经尝试过这些解决方案,但它们从未奏效过:

JSON Parsing in Swift 3

Correctly Parsing JSON in Swift 3

Parsing JSON using Swift 3

1 个答案:

答案 0 :(得分:7)

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)
        }
    }
}
  1. result属于Any类型
  2. 将其投入字典 - [String : AnyObject]
  3. 提取data并投射到字典数组 - [[String : AnyObject]]