JSON-Swift中字典的可解码
我试图在JSON-Swift中字典的可解码,json,dictionary,decodable,Json,Dictionary,Decodable,我试图在JSON数据中使用Decodable作为dictionary,但我得到了以下错误:1)类型“Customer”不符合协议“Decodable”,2)使用未声明的类型“Address”。任何帮助都会很好 struct Customer : Decodable { var firstName : String var lastName : String var address : Address } struct CustomersResponse : Decoda
JSON
数据中使用Decodable
作为dictionary
,但我得到了以下错误: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)
地址
和地理
字典
被视为嵌套对象。由于使用了未声明的类型“地址”错误,您得到的类型“Customer”不符合协议“Decodable”错误。因此,首先,您需要通过声明地址
类型来消除第二个错误。但是,如果不声明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
}