1

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) -> 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

2 Answers 2

2

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"]
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This returns a fatal error "unexpectedly found nil while unwrapping an Optional value" the 'dicObj["payment"]' returns nil
you can use like this .. dicObj["payment"] as! NSArray
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 }
You can use like this to show values on your cell..... cell.textLabel?.text = PlanStorage[indexPath.row] [description]
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....
0

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()

9 Comments

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
create a property payments in your class
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!
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
func numberOfSectionsInTableView(tableView: UITableView) -> Int { tableView.reloadData() return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.reloadData() return PlanStorage.count }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.