0

I'm trying to understand the best way to parse a json file with the Codable.

This is the json structure.

{
    "type": "Feature",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "coordinates": [
                    [10.23, 48.32],
                    [10.24, 48.33],
                    [10.25, 48.34],
                    [10.26, 48.35],
                    [10.27, 48.36]
                ]
            }
        }
    ]
}

What I need is the list of coordinates. I tried to implement this structures but I have some problems.

struct Root: Codable {
    let features: [Features]
}

struct Features: Codable {
    let geometry: [Coordinates]
}

struct Geometry: Codable {
    let coordinates: [Coordinates]
}

struct Coordinates: Codable {
    let latitude: [Double]
    let longitude: [Double]
}

Then I call the JSONDecoder function like this

let coordinates = try JSONDecoder().decode(Root.self, from: data)

I think that the error is that the coordinates are in a sublist. I'm new in this world so sorry if the question is a little bit dummy but I haven't find an explanation by my self.

2
  • 1
    What exactly is the error? Commented Apr 2, 2022 at 11:14
  • 2
    This is GeoJSON. Use MKGeoJSONDecoder Commented Apr 2, 2022 at 14:16

1 Answer 1

3

you were almost there. Try this:

struct Root: Codable {
    let features: [Feature]
}

struct Feature: Codable {
    let geometry: Geometry
}

struct Geometry: Codable {
    let coordinates: [[Double]]
}

and:

let root = try JSONDecoder().decode(Root.self, from: data)

and:

for feature in root.features {
    let coords = feature.geometry.coordinates
    print("\(coords)")
}

PS: your data seems to be GeoJSON. Read-up on Swift GeoJSON and how to decode it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.