简体   繁体   English

JSON中字典的可解码-Swift

[英]Decodable for Dictionaries in JSON - Swift

I am trying to use Decodable for Dictionaries in JSON data, but I get these errors: 1) Type 'Customer' does not conform to protocol 'Decodable' and 2) Use of undeclared type 'Address'. 我正在尝试在JSON数据中为Dictionaries使用Decodable Dictionaries ,但出现以下错误:1)类型“ Customer”不符合协议“ Decodable”和2)使用未声明的类型“ Address”。 Any help would be great. 任何帮助都会很棒。

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)

The address and geo Dictionaries are considered Nested Objects . addressgeo Dictionaries被视为嵌套对象 You are getting the Type 'Customer' does not conform to protocol 'Decodable' Error because of the Use of undeclared type 'Address' Error. 由于使用未声明的类型“地址”错误,您将获得“客户”类型不符合协议“可解码 错误。 So first, you need to eliminate that second error by declaring the Address type. 因此,首先,您需要通过声明Address类型来消除第二个错误。 But, then you will get two new errors if you don't declare Geo , as well. 但是,如果您同时不声明Geo ,那么将收到两个新错误。 Add the following code to the top of your project to eliminate any errors and produce the proper output. 将以下代码添加到项目的顶部,以消除任何错误并产生正确的输出。

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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