如何在Swift中循环遍历JSON对象并将其视为字符串

3

我刚开始学习swift编程,目前能够从JSON中获取单个值,但无法通过循环遍历数组来获取所有的值。所以我的问题是如何获取所有值并将其视为浮点数或字符串。

这是我的代码:

 let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    //print(myJson)

                    for items in myJson [AnyObject] {
                        print(items)
                    }

                    //here is the single value part, it looks for the rates then it puts it in label.

                    if let  rates = myJson["rates"] as? NSDictionary{


                        if let currency = rates["AUD"]{


                        print(currency);

                       self.label.text=String(describing: currency)


                        }





                    }

                }

                catch
                {


                }
            }
        }
    }
    task.resume()

这行代码对我来说没有意义:for items in myJson [AnyObject] 我不认为它能编译通过。@aircraft的答案在定义myJSON常量的那一行将JSON结果转换为正确的类型。除了使用as!强制转换之外,这是更好的方法。(我会将其重写为一个guard语句,如果转换失败就退出,因为远程服务器数据的格式可能会改变。) - Duncan C
一如既往,mutableContainers 在 Swift 中完全没有意义。 - vadian
3个回答

2

尝试使用这段代码:

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

    self.getJson()
}

func getJson(){

    let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                        //Dic
                        guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return}
                        //print(myJson)

                        for items in myJson {
                            print(items)
                        }

                        //here is the single value part, it looks for the rates then it puts it in label.

                        if let  rates = myJson["rates"] as? NSDictionary{


                            if let currency = rates["AUD"]{


                                print(currency);

                               // self.label.text=String(describing: currency)


                            }


                        }

                    }

                    catch
                    {


                    }
                }
            }
        }
        task.resume()
    }
}

控制台中的结果如下所示:
enter image description here

myJson是您想要的字典。


不错的回答,除了这一行应该是一个守卫语句:guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return} - Duncan C
1
您的代码使用了强制转换,这对于来自远程服务器的数据并不安全,因为您无法保证来自远程站点的数据格式。 - Duncan C
@Duncan C,感谢您的建议,您的建议非常周到和棒极了。 - aircraft

1
我强烈建议您使用SwiftyJSON来处理JSON。它非常易于学习和使用。
首先,您应该通过CocoaPods(或其他任何方式)安装SwiftyJSON。然后,您可以像下面这样简单地编写代码:
let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {

                // Initialization
                let myJson = JSON(data: content)

                // Getting a string using a path to the element
                self.label.text = myJson["rates"]["AUD"].stringValue

                // Loop test
                for (key,value):(String, JSON) in myJson["rates"] {
                    print("key is :\(key), Value:\(value.floatValue)")
                }
            }
        }
    }
    task.resume()

现在我让它工作了!但现在它无法在标签中显示整个列表,只会显示最后一条记录。当我打印时,它会显示所有内容,请问有什么方法可以修正这个问题吗? - jacob de Wit

0

试一下这个:

    if let currency = rates["AUD"] as? NSDictionary{
         for(key,value) in currency {
            // the key will be your currency format and value would be your currency value
         }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接