[英]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.