0

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
   ]
]
2
  • What error does it give you? Commented Apr 27, 2018 at 15:26
  • As I mentioned above: Type 'Feature' does not conform to protocol 'Encodable @Andy Commented Apr 27, 2018 at 15:27

2 Answers 2

2

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)
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

It's working perfectly! Thank you very much! I'll mark it as an answer!
I got another question about this. By using this code above, i'm getting only the first object of the coordinates array. I tried to make another struct but it all gives me the value of nil
Look at the answer from @vadian. It pulls all the coordinates as an array
Yeah I tried it out, but it didn't seem to work when I had to grab more information like both properties values + coordinates. I'll tried using new structs as vadian said, because the coordinates were in an array in an array.
2

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

1 Comment

Do you have example for using the model as codable where we can use the model for both coredata saving model and json parsing model ? I don't want create custom subclass for code data entity and separate model object. I want to use one (1) model class for both which can subclass both codable and nsmanagedobject or anything. In our old project, we used 2 models. And before converting we use mapper method to convert nsmanageobejct to nsobject (core data fetch) and nsobject to nsmanagedobejct (core data save). I was struggling for such example for somedays :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.