Title: Extracting values from Json Data in Swift iOS9
Tags: ios;json;uitableview;dictionary
Question: I have the following JSon Data retrieved from the server and i want to extract the value name and store them in an array or dictionary as a model in my app. The issue is that the value returned its self is in a form of another dictionary. How can i extract values of frequency,description and amount and update them to my tableview. Below is my Json Data format that i get from the server request. I am new to swift and the concept of dictionaries and Arrays is quiet confusing to me
"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;
I want to store them locally in a dictionary or an array, and update them to my tableview.
Here also is my code to fetch the data from server
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -&gt; 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()
I am stuck here how to extract the values that i get in the dictionary. Thanks in advance

Here is the accepted answer: Dictionary it's a key-value storage where value in your case have AnyObject type.
To convert data into Dictionary or Array you can use
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
then create payments array
if let payments = jsonResult as? Array{
*iterate here all payments
If you want to use for (key, value) in plan_list you need to change it's to for (key, value) in plan_list.enumerate()
Comment for this answer: I managed to get the Json Data....Any idea how i can populate the data into the tableview? Seems not to work on my side. Thanks
Comment for this answer: I tried to call reloadData in every datasource method `self.PlanStorage.append(display_price)
self.PlanStorage.append(display_name)` Here PlanStoage is where am storing the data and is of an array of strings. `        cell.textLabel?.text = PlanStorage[indexPath.row]
` This is the code to populate the data but is not working
Comment for this answer: `func numberOfSectionsInTableView(tableView: UITableView) -> Int {
tableView.reloadData()
return 1;
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.reloadData()
return PlanStorage.count
Comment for this answer: `func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("choosePlan", forIndexPath: indexPath) as! UITableViewCell
tableView.reloadData()
cell.textLabel?.text = PlanStorage[indexPath.row]

return cell
Comment for this answer: create a property  **payments** in your class
Comment for this answer: sorry, then put all data to **payments** property and call reloadData() in table view  dataSource methods you can get data using 'if let payment = self.payments as? NSDictionary { cell.label.text = payment["description"] as? String}' don't forget you have a integer also!
Comment for this answer: remove reloadData here func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.reloadData() return PlanStorage.count } you need to reloadData after append all planStorages here;
Comment for this answer: self.PlanStorage.append(display_name)
Comment for this answer: and use a debugger to check all breakpoints, you can see which data in PlanStorage currently. Then you can understand whats wrong

Here is another answer: Hi You can iterrate your result as following:
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"]
}
Comment for this answer: This returns a fatal error "unexpectedly found nil while unwrapping an Optional value" the 'dicObj["payment"]'  returns nil
Comment for this answer: I got it to work....thank you, can you recommend how i can populate the above data in the tableviewcell? It seems not working on my side. Here is my code
`func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("choosePlan", forIndexPath: indexPath) as!UITableViewCell
cell.textLabel?.text = PlanStorage[indexPath.row]
return cell
}`
Comment for this answer: you can use like this .. dicObj["payment"] as! NSArray
Comment for this answer: You can use like this to show values on your cell.....                  cell.textLabel?.text = PlanStorage[indexPath.row] [description]
Comment for this answer: And please check key before assigning to cell because it may be nil. If its nil then it may crash. So please make check for it....

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:11/22/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ios><json><uitableview><dictionary>', 'Title': 'Extracting values from Json Data in Swift iOS9', 'ViewCount': 242, 'id': 40736924, 'user_AboutMe': None, 'user_AccountId': 5684126.0, 'user_DisplayName': 'Arnold', 'user_Reputation': 103.0, 'user_Views': 16.0, 'user_id': 4494215.0}}