且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Codable解析嵌套的JSON数据

更新时间:2022-05-17 00:06:22

编译器给您的错误是因为您的对象不符合Encodable

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

如果您只需要使用JSON->对象,而不必使用其他方法,则可以使用Decodable代替Codable.

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

Codable需要符合Encodable,因此您还必须实现encode(to encoder: Encoder)

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.

内部几何对象与外部对象的键不同,因此需要单独的CodingKey来传递.您还需要比当前的位置更深一层.

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.

此版本适用于您所质疑的json:

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