JSON - Swift 中的字典可解码

Decodable for Dictionaries in JSON - Swift

我正在尝试将 Decodable 用于 JSON 数据中的 Dictionaries,但出现以下错误:1) 类型 'Customer' 不符合协议 'Decodable' 和 2) 使用未声明的类型 'Address'。任何帮助都会很棒。

struct Customer : Decodable {
    var firstName : String
    var lastName : String
    var address : Address
}

struct CustomersResponse : Decodable {
    var customers : [Customer]
}

let json = """

{
    "customers":[
        {
            "firstName" : "Henry",
            "lastName" : "Collins",
            "address" : {
                "street" : "1200 Highland Ave",
                "city" : "Houston",
                "state" : "TX",
                "geo" : {
                    "latitude" : 29.76,
                    "longitude" : -95.36
                }
            }
        }

    ]

}

""".data(using: .utf8)!

let customersResponse = try! 
JSONDecoder().decode(CustomersResponse.self, from: json)
print(customersResponse)

addressgeo Dictionaries 被视为 嵌套对象 。由于 使用未声明的类型 'Address'[=,您收到 Type 'Customer' does not conform to protocol 'Decodable' 错误21=] 错误。所以首先,您需要通过声明 Address 类型来消除第二个错误。但是,如果您不声明 Geo,您也会收到两个新错误。将以下代码添加到项目的顶部以消除任何错误并生成正确的输出。

struct Geo : Decodable {
    var latitude : Double
    var longitude : Double
}


struct Address : Decodable {
    var street : String
    var city : String
    var state : String
    var geo : Geo
}