gpt4 book ai didi

ios - 在 Swift iOS9 中从 Json 数据中提取值

转载 作者:行者123 更新时间:2023-12-01 19:59:14 24 4
gpt4 key购买 nike

我从服务器检索了以下 JSon 数据,我想提取值名称并将它们作为模型存储在数组或字典中。问题是返回的值本身是另一个字典的形式。我如何提取频率、描述和数量的值并将它们更新到我的表格 View 。下面是我从服务器请求中获得的 Json 数据格式。我是 swift 新手,字典和数组的概念让我很困惑

{
"payment" = (
{
amount = 100;
currency = USD;
description = "Awesome Videos";
frequency = Day;
},
{
amount = 500;
currency = USD;
description = "Awesome Videos";
frequency = Week;
},
{
amount = 3000;
currency = USD;
description = "Awesome Videos";
frequency = Months;
}
);

}

我想将它们本地存储在字典或数组中,并将它们更新到我的表格 View 中。

这也是我从服务器获取数据的代码
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if (data != nil){
print(data)
do {

// let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

print(jsonResult)
print(jsonResult["payment_plans"])



if let plan_list = jsonResult as? NSDictionary{
print("got dictionary")

for (key, value) in plan_list
{
print(value)
print("printing keys")
print(key)

if let plans = value as? NSDictionary
{
print("printing values")
print(plans)
print(plans["currency"])
}
}
}

} catch{
print("Json Serialization failed")
}
}

}
/*
if (response != nil){
print(response)
}
else{
print(error)
}
}
*/
task.resume()
}

我被困在这里如何提取我在字典中得到的值。提前致谢

最佳答案

嗨,您可以按以下方式迭代您的结果:

if((jsonResult) != nil) {
let swiftyJsonVar = jsonResult!
do {
if let dicObj = swiftyJsonVar as? NSDictionary {
print("Response is dictionary")
print(dicObj)
let arrObj = dicObj["payment"] as NSArray
// Then iterate your arrObj and do as per your need.
//for eg.
arrObj[0]["description"]
}
}
}

关于ios - 在 Swift iOS9 中从 Json 数据中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40736924/

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