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

时间:2017-01-15 23:47:39

标签: ios json swift

我刚刚开始使用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()

3 个答案:

答案 0 :(得分: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是你想要的字典。

答案 1 :(得分: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()

答案 2 :(得分: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
         }
    }