[英]Extracting values from Json Data in Swift iOS9
我从服务器检索了以下JSon数据,我想提取值名称并将其作为模型存储在数组或字典中,作为我的应用程序。 问题在于返回的自身值是另一种字典的形式。 如何提取频率,描述和数量的值并将其更新到我的表视图中。 以下是我从服务器请求中获得的Json数据格式。 我是新手,字典和数组的概念让我很困惑
{
"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;
}
);
}
我想将它们存储在本地的字典或数组中,然后将它们更新到我的tableview中。
这也是我从服务器获取数据的代码
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"]
}
}
}
字典是key-value
存储,其中您的值具有AnyObject类型。
要将数据转换为Dictionary
或Array
,可以使用
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
然后创建付款数组
if let payments = jsonResult as? Array{
*iterate here all payments
}
如果要for (key, value) in plan_list
需要for (key, value) in plan_list.enumerate()
其更改为for (key, value) in plan_list.enumerate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.