parsing json into an array in swift 3

18,210

Solution 1

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

Solution 2

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

Share:
18,210
Rodrigo Schreiner
Author by

Rodrigo Schreiner

Updated on June 05, 2022

Comments

  • Rodrigo Schreiner
    Rodrigo Schreiner almost 2 years

    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

  • Rodrigo Schreiner
    Rodrigo Schreiner over 7 years
    Hi Niko, when I run the code I get this Could not cast value of type 'NSTaggedPointerString' (0x1027f1b90) to 'NSNumber' (0x101dfa300). in this line let teamId: Int = liquidLocations[i]["locationid"] as! Int!
  • Niko Adrianus Yuwono
    Niko Adrianus Yuwono over 7 years
    @RodrigoSchreiner Looks like in Swift 3 id is translated to Any rather than AnyObject, could you test my updated answer?
  • Rodrigo Schreiner
    Rodrigo Schreiner over 7 years
    Hi Niko, I just tested the updated version and I got this now Could not cast value of type 'NSTaggedPointerString' (0x10aef7b90) to 'NSNumber'
  • Niko Adrianus Yuwono
    Niko Adrianus Yuwono over 7 years
    @RodrigoSchreiner OK then my assumption about JSONSerialization map the value into NSString seems correct, try the updated answer again where I cast to NSString first then get the integerValue