gpt4 book ai didi

ios - 快速将JSON值解析为全局数组

转载 作者:行者123 更新时间:2023-11-28 09:25:17 27 4
gpt4 key购买 nike

我一直试图让下面的代码返回一个可以在UIPickerView类“title for Rows”中使用的信息数组。这段代码不起作用,我现在这样做了,当我运行打印脚本时,它确实从我的JSON值返回了所有值的列表。解析的JSON示例。我已经看了两个晚上的YouTube视频和相关信息。任何帮助都很好。我找到的所有内容都将解析的JSON结果发送到表视图。

       {
date = "2017-05-01";
"financial_institution" = "Your Neighbourhood C.U.";
"five_year" = "2.79";
"four_year" = "3.15";
key = 86;
"one_year" = "2.79";
"six_months" = 0;
"three_year" = "3.09";
"two_year" = "2.89";
"variable_rate" = 0;
}

)
        func getJSONData()
{
let url = URL(string:"")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

if error != nil {
print("error")
}

else {

if let mydata = data {

do {

let myJson = try JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

print(myJson)

var lenderName = myJson["financial_institution"]

for i in lenderName {

var lender = "financial_institution"
lender += "\(i)"
var lenderList = myJson[lender].string as String!

lenderNamesArray.append(lenderList)
}


}

catch {
// catch error
}
}
}
}

task.resume()

}

最佳答案

我假设您正在分析的JSON包含许多贷方,例如:

    {
"lenders": [
{
"date": "2017-05-01",
"financial_institution": "Your Neighbourhood C.U.",
"five_year": "2.79",
"four_year": "3.15",
"key": "86",
"one_year": "2.79",
"six_months": "0",
"three_year": "3.09",
"two_year": "2.89",
"variable_rate": "0"
},
{
"date": "2017-05-01",
"financial_institution": "Your Neighbourhood C.U.",
"five_year": "2.79",
"four_year": "3.15",
"key": "86",
"one_year": "2.79",
"six_months": "0",
"three_year": "3.09",
"two_year": "2.89",
"variable_rate": "0"
},
{
"date": "2017-05-01",
"financial_institution": "Your Neighbourhood C.U.",
"five_year": "2.79",
"four_year": "3.15",
"key": "86",
"one_year": "2.79",
"six_months": "0",
"three_year": "3.09",
"two_year": "2.89",
"variable_rate": "0"
}]
}

因为我不能用你的数据来测试这个,所以你的代码应该是这样的:
func getJSONData()
{
let url = URL(string: "");

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

if error != nil
{
print("error")
}

else
{
if let mydata = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

let lenders = myJson["lenders"] as! [AnyObject];

for lender in lenders
{
// This is how you access the data
let institution = lender["financial_institution"] as! String;
let fiveYear = lender["five_year"] as! CGFloat;

// Store the data however you are doing it
}
}

catch {
// catch error
}
}
}
}

task.resume()

}

关于ios - 快速将JSON值解析为全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43992153/

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