How to covert String to Array of Object in Swift

Viewed 46

This is my first Question so I don't know a better way to ask it. My question is in Swift I am converting this String:

  let points = "[{\"lat\":\"33.6240836\", \"lng\":\"73.0686886\"},{\"lat\":\"33.6235471\", \"lng\":\"73.0686249\"},{\"lat\":\"33.6234177\" , \"lng\":\"73.0681210\"},{\"lat\":\"33.6232655\" , \"lng\":\"73.0676921\"},{\"lat\":\"33.6241488\" , \"lng\":\"73.0683039\"}]"

By using the method:

let data = points.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
        {
           print(jsonArray) // use the json here
            
        } else {
            print("bad json")
        }
        
    } catch let error as NSError {
        print(error)
    }

But it returns:

[["lng": 73.0686886, "lat": 33.6240836], ["lng": 73.0686249, "lat": 33.6235471], ["lng": 73.0681210, "lat": 33.6234177], ["lng": 73.0676921, "lat": 33.6232655], ["lng": 73.0683039, "lat": 33.6241488]]

While what I need is:

[{"lng": "73.0686886", "lat": "33.6240836"}, {"lng": "73.0686249", "lat": "33.6235471"}, {"lng": "73.0681210", "lat": "33.6234177"}, {"lng": "73.0676921", "lat": "33.6232655"}, {"lng": "73.0683039", "lat": "33.6241488"}]

Can any body helps me how to achieve it in swift?

1 Answers

You asked about Array of Object so declare a struct and decode the JSON with Decodable

let points = "[{\"lat\":\"33.6240836\", \"lng\":\"73.0686886\"},{\"lat\":\"33.6235471\", \"lng\":\"73.0686249\"},{\"lat\":\"33.6234177\" , \"lng\":\"73.0681210\"},{\"lat\":\"33.6232655\" , \"lng\":\"73.0676921\"},{\"lat\":\"33.6241488\" , \"lng\":\"73.0683039\"}]"


struct Point : Decodable {
    let lat, lng: String
}

let data = Data(points.utf8)
do {
    let jsonArray = try JSONDecoder().decode([Point].self, from: data)
    print(jsonArray)
} catch { // never cast to NSError
    print(error)
}
Related