如何在Swift 3中使用循环打印JSON值? [英] How to print JSON values using a loop in Swift 3?

查看:173
本文介绍了如何在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
}

}

但是我不知道如何遍历它们

我已经尝试过这些解决方案,但是它们从未起作用:

在Swift 3中进行JSON解析

在Swift 3中正确解析JSON

使用Swift 3解析JSON

解决方案

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. resultAny类型
  2. 将其发布到字典中-[String : AnyObject]
  3. 提取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:

JSON Parsing in Swift 3

Correctly Parsing JSON in Swift 3

Parsing JSON using 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)
        }
    }
}

  1. result is of Any type
  2. Cast it into Dictionary - [String : AnyObject]
  3. Extract data and cast to Array of Dictionaries - [[String : AnyObject]].

这篇关于如何在Swift 3中使用循环打印JSON值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆