Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing json into an array in swift 3

Tags:

json

ios

swift3

I am new on swift and I am getting a json back from a request but I can not parse. I am trying to get the json info and create coordinates to use on mapkit with annotations as well

Below is the json I get back

{
    coord =     [
                {
            islocationactive = 1;
            latitude = "37.8037522";
            locationid = 1;
            locationsubtitle = Danville;
            locationtitle = "Schreiner's Home";
            longitude = "121.9871216";
        },
                {
            islocationactive = 1;
            latitude = "37.8191921";
            locationid = 2;
            locationsubtitle = "Elementary School";
            locationtitle = Montair;
            longitude = "-122.0071005";
        },
                {
            islocationactive = 1;
            latitude = "37.8186077";
            locationid = 3;
            locationsubtitle = "Americas Eats";
            locationtitle = "Chaus Restaurant";
            longitude = "-121.999046";
        },
                {
            islocationactive = 1;
            latitude = "37.7789669";
            locationid = 4;
            locationsubtitle = "Cheer & Dance";
            locationtitle = Valley;
            longitude = "-121.9829908";
        }
    ] }

and my code to try to parse is this

 let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in

            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                var teamJSON: NSDictionary!

                teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                print(teamJSON)
                //getting the JSON array teams from the response
                let liquidLocations: NSArray = teamJSON["coord"] as! NSArray

                //looping through all the json objects in the array teams
                for i in 0 ..< liquidLocations.count{

                    //getting the data at each index
      //              let teamId:Int = liquidLocations[i]["locationid"] as! Int!

                }

            } catch {
                print(error)
            }
        }
        //executing the task
        task.resume()

but not that I try works. I want to get the latitude, longitude and create an annotationn on the map

Thanks for the help

like image 910
Rodrigo Schreiner Avatar asked Sep 29 '16 01:09

Rodrigo Schreiner


2 Answers

You can try with below code its same as @Niko Adrianus Yuwono but made some changes so you will get teamid as integer

    do {
        let data : NSData = NSData() // change your data variable as you get from webservice response
        guard let teamJSON =  try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any],
            let liquidLocations = teamJSON["coord"] as? [[String: Any]]
            else { return }

        //looping through all the json objects in the array teams
        for i in 0 ..< liquidLocations.count{
            let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
            print(teamId)
        }

    } catch {
        print(error)
    }
like image 71
Pavan Gandhi Avatar answered Oct 13 '22 00:10

Pavan Gandhi


Try this

        do {
            guard let teamJSON =  try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any],
                let liquidLocations = teamJSON["coord"] as? [[String: Any]]
                else { return }

            //looping through all the json objects in the array teams
            for i in 0 ..< liquidLocations.count{
                let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
            }

        } catch {
            print(error)
        }

The key is not to use NSDictionary and NSArray because it's not strongly-typed (Although you can make it strongly-typed too) use Swift's array and Dictionary where you can use [Element Type] for array and [Key: Value] for dictionary

like image 28
Niko Adrianus Yuwono Avatar answered Oct 13 '22 00:10

Niko Adrianus Yuwono