gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:02:50 25 4
gpt4 key购买 nike

我刚开始使用 swift 进行编码,现在我可以从 JSON 中获取单个值,但我似乎无法通过遍历数组从中获取所有值。所以我的问题是如何获取所有值并将其视为 float 或字符串。

这是我的代码:

 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()

最佳答案

试试这段代码:

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 就是你想要的字典。

关于ios - 如何遍历 JSON 对象并将其视为字符串 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com