简体   繁体   中英

Using Codable to parse nested JSON data

I'm trying to use Codable to parse JSON data. But having some problems when it comes down to an object with arrays. I've been trying to follow following answer , but i'm getting an error Type 'Feature' does not conform to protocol 'Encodable'

The JSON data I want are the latitude and longitude data, but i'm struggling to hard to learn Codable . I can also add that I tried to grab the id and it worked fine, but when i'm trying to go deeper, it just gives me an error.

Any advice? I do want to use Codable and not JSONSerialization .

My struct (So far)

struct Features: Codable {
    var features: [Feature]
}

struct Feature: Codable {
    var lat: Double
    var long: Double


    enum CodingKeys: String, CodingKey {
        case geometry
    }


    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let geometry = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .geometry)
        var coordinates = try geometry.nestedUnkeyedContainer(forKey: .geometry)
        long = try coordinates.decode(Double.self)
        lat = try coordinates.decode(Double.self)

    }
}

JSON RESPONSE

{  
   "type":"FeatureCollection",
   "totalFeatures":1761,
   "features":[  
      {  
         "type":"Feature",
         "id":"LTFR_P_RORELSEHINDRADE.3179814",
         "geometry":{  
            "type":"LineString",
            "coordinates":[  
               [  
                  17.929374,
                  59.387507
               ],
               [  
                  17.929364,
                  59.387493
               ]
            ]
         },
         "geometry_name":"GEOMETRY",
         "properties":{  
            "FID":3179814,
            "FEATURE_OBJECT_ID":2406812,
            "FEATURE_VERSION_ID":1,
            "EXTENT_NO":2,
            "VALID_FROM":"2008-10-09T22:00:00Z",
            "CITATION":"0180 2008-09122",
            "STREET_NAME":"Visbyringen",
            "CITY_DISTRICT":"Rinkeby",
            "PARKING_DISTRICT":"<Område saknas>",
            "ADDRESS":"Visbyringen 4",
            "VF_METER":12,
            "VF_PLATS_TYP":"Reserverad p-plats rörelsehindrad",
            "RDT_URL":"https://rdt.transportstyrelsen.se/rdt/AF06_View.aspx?BeslutsMyndighetKod=0180&BeslutadAr=2008&LopNr=09122"
         }
      }
   ]
}

The interested data

"coordinates":[  
   [  
      17.929374,
      59.387507
   ],
   [  
      17.929364,
      59.387493
   ]
]

The error the compiler is giving you is because your object doesn't conform to Encodable

If you just need to go JSON -> object and not the other way around then you can use Decodable instead of Codable .

Codable requires conformance to Encodable so you would also have to implement encode(to encoder: Encoder)

After you fix that then you also need to fix your parsing of the nested containers.

Your inner geometry object has different keys than your outer object so you need a separate CodingKey to pass. You also need to go one level deeper than you currently are to get to your coordinates.

This version should work for the json in your question:

struct Features: Decodable {
    var features: [Feature]
}

struct Feature: Decodable {
    var lat: Double
    var long: Double

    enum CodingKeys: String, CodingKey {
        case geometry
    }

    enum GeometryKeys: String, CodingKey {
        case coordinates
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let geometry = try values.nestedContainer(keyedBy: GeometryKeys.self, forKey: .geometry)
        var coordinates = try geometry.nestedUnkeyedContainer(forKey: .coordinates)

        var longLat = try coordinates.nestedUnkeyedContainer()
        long = try longLat.decode(Double.self)
        lat = try longLat.decode(Double.self)
    }
}

First of all if you want only to decode JSON adopt only Decodable . If you adopt Codable and write a custom initializer you have to write also an encoder method. This is the message of the error.

I recommend to decode the JSON into separate structs. This requires much less code. Write an extension of CLLocationCoordinate2D as a wrapper for the coordinates to adopt Decodable

import CoreLocation

extension CLLocationCoordinate2D : Decodable {
    public init(from decoder: Decoder) throws {
        var arrayContainer = try decoder.unkeyedContainer()
        let lat = try arrayContainer.decode(CLLocationDegrees.self)
        let lng = try arrayContainer.decode(CLLocationDegrees.self)
        self.init(latitude: lat, longitude: lng)
    }
}

The rest are only a few lines

struct Features: Decodable {
    var features: [Feature]
}

struct Feature: Decodable {
    let geometry : Geometry
}

struct Geometry: Decodable {
    let coordinates : [CLLocationCoordinate2D]
}

You get the coordinates with

do {
    let result = try JSONDecoder().decode(Features.self, from: data)
    for feature in result.features {
        print(feature.geometry.coordinates)
    }
} catch { print(error) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM