Swift 4中的JSON解码

时间:2018-03-07 17:39:50

标签: json swift jsondecoder

我正在尝试将以下JSON从Met Office转换为Swift 4中的对象,但我遇到了错误。我的计划是在解码JSON后存储在Core Data中。以下是返回的一些JSON

let json = """
{
    "Locations":
        {
            "Location":
                [
                    {
                        "elevation": "50.0",
                        "id": "14",
                        "latitude": "54.9375",
                        "longitude": "-2.8092",
                        "name": "Carlisle Airport",
                        "region": "nw",
                        "unitaryAuthArea": "Cumbria"
                    },
                    {
                        "elevation": "22.0",
                        "id": "26",
                        "latitude": "53.3336",
                        "longitude": "-2.85",
                        "name": "Liverpool John Lennon Airport",
                        "region": "nw",
                        "unitaryAuthArea": "Merseyside"
                    }
                ]
        }
}
""".data(using: .utf8)!

我创建了一个用于将数据转换为:

的结构
struct locations: Decodable {
    var Locations: [location]
    struct location: Decodable {
        var Location: [MetOfficeLocation]
        struct MetOfficeLocation: Decodable {
            var elevation: String
            var id: String
            var latitude: String
            var longitude: String
            var obsSource: String?
            var name: String
            var region: String
            var area: String

            private enum CodingKeys: String, CodingKey {
                case elevation
                case id
                case latitude
                case longitude
                case obsSource
                case name
                case region
                case area = "unitaryAuthArea"
            }
        }
    }
}

然后我使用JSONDecoder进行转换:

let place = try JSONDecoder().decode([Location].self, from: json)
for i in place {
    print(i.Location[0].name)
}

我收到一个keyNotFound错误,没有与关键位置相关的值(\“locations \”)。“我很困惑,因为我不确定应该与位置搭配什么值,因为它只是位置

谢谢

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。但最简单的可能是创建表示JSON每个级别的结构:

struct Location: Codable {
    let elevation: String
    let id: String
    let latitude: String
    let longitude: String
    let name: String
    let region: String
    let area: String
    private enum CodingKeys: String, CodingKey {
        case elevation, id, latitude, longitude, name, region
        case area = "unitaryAuthArea"
    }
}

struct Locations: Codable {
    let locations: [Location]
    enum CodingKeys: String, CodingKey {
        case locations = "Location"
    }
}

struct ResponseObject: Codable {
    let locations: Locations
    enum CodingKeys: String, CodingKey {
        case locations = "Locations"
    }
}

do {
    let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)
    print(responseObject.locations.locations)
} catch {
    print(error)
}