我从服务器检索了以下JSon数据,我想提取值名称并将它们存储在数组或字典中作为我的应用程序中的模型。问题是返回它自己的值是另一个字典的形式。如何提取频率,描述和数量的值,并将它们更新到我的tableview。下面是我从服务器请求获得的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;
}
);
}
我想将它们本地存储在字典或数组中,并将它们更新为我的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()
}
我被困在这里如何提取我在字典中获得的值。提前致谢
答案 0 :(得分:2)
您好您可以按照以下步骤操作结果:
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"]
}
}
}
答案 1 :(得分:0)
字典它是一个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()