简体   繁体   中英

Extracting values from Json Data in Swift iOS9

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

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"]
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM