Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse Simple Dictionary Array from HTTP Request

I have a JSON response in the following format:

{
  "coordinates": [
    "-0.88676",
    "51.47533"
  ],
[
    "-0.88646",
    "51.47549"
]
}

I am struggling to parse this data and append each coordinates value into an array.
I can see that this is a dictionary array but if I try to parse as a dictionary I get an error. Parsing as an array returns just the one item which essentially is the json as a single entry.

I am not adding any of my code as I believe this would be fruitless, because I have been unable to achieve what I need without errors, and have tried numerous options, all without success.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

At the moment your JSON is not valid JSON data. But that might be a typo.

If we change this into valid JSON…

{
  "coordinates": [
    [
      "-0.88676",
      "51.47533"
    ],
    [
      "-0.88646",
      "51.47549"
    ]
  ]
}

Then you could represent this as a struct like…

struct Response: Decodable {
  let coordinates: [[String]] // <- this is a 2D array of coordinate pairs.

  var locations: [CLLocation2D] {
    coordinates
      .map { $0.compactMap(Double.init) }
      .filter { $0.count < 2 }
      .map { ($0[0], $0[1]) }
      .map(CLLocation2D.init(latitude:longitude:))
  } // Something like that anyway
}

Then you can decode it like…

let data = // get the data from the network or a file etc...
let response = JSONDecoder().decode(Response.self, from: data)

That should give you the struct you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading