我尝试解码来自Google API服务器的数据,但它们总是会出现
之类的错误typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:“ rows”,intValue:nil),_JSONKey(stringValue: “索引0”,intValue:0),CodingKeys(字符串值:“ elements”,intValue: nil),_ JSONKey(stringValue:“索引0”,intValue:0), CodingKeys(stringValue:“ distance”,intValue:nil)],debugDescription: “打算对数组进行解码,但是找到了一个字典。”, 底层错误:nil))
我没有任何变体实现
{
"destination_addresses": [
"Абая-Саина, просп. Абая, Алматы, Казахстан"
],
"origin_addresses": [
"г. Алматы, ул. Джандосова, 6, уг. ул. Манаса, Алматы, Казахстан"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "7,2 км",
"value": 7241
},
"duration": {
"text": "16 мин.",
"value": 980
},
"status": "OK"
}
]
}
],
"status": "OK"
}
这是我的关键结构
struct Distance:Codable {
var destination_addresses : [String]?
var origin_addresses : [String]?
var rows : [row]?
var status : String?
enum CodingKeys:String,CodingKey{
case destination_addresses = "destination_addresses"
case origin_addresses = "origin_addresses"
case rows = "rows"
case status = "status"
}
}
struct row:Codable {
var elements : [elements]?
enum CodingKeys:String,CodingKey {
case elements = "elements"
}
}
struct elements:Codable {
var distance : [distance]?
var duration : [duration]?
var status : String?
enum CodingKeys:String,CodingKey {
case distance = "distance"
case duration = "duration"
case status = "status"
}
}
struct distance:Codable {
var text : String?
var value : Int?
enum CodingKeys:String,CodingKey {
case text = "text"
case value = "value"
}
}
struct duration:Codable {
var text : String?
var value : Int?
enum CodingKeys:String,CodingKey {
case text = "text"
case value = "value"
}
}
我的解码
let root = try decoder.decode(Distance.self, from: data)
答案 0 :(得分:0)
您可以尝试
struct Root: Codable {
let destinationAddresses, originAddresses: [String]
let rows: [Row]
let status: String
enum CodingKeys: String, CodingKey {
case destinationAddresses = "destination_addresses"
case originAddresses = "origin_addresses"
case rows, status
}
}
struct Row: Codable {
let elements: [Element]
}
struct Element: Codable {
let distance, duration: Distance // your problem is here
let status: String
}
struct Distance: Codable {
let text: String
let value: Int
}
let root = try? decoder.decode(Root.self, from: data)
为
var distance : [distance]?
var duration : [duration]?
是字典而不是数组
同样,distance
和duration
无需为相同的内容创建2个strcut,因为仅更改键就足够了
此外,如果您不更改键名,请不要在结构中使用enum CodingKeys: String, CodingKey {
,因为那样将无用