我从服务器收到json响应,然后将这个json数据解码为我的模型类。但显示错误“由于格式不正确,无法读取数据”。我第一次在iOS中使用此功能。我实际上不知道如何解决此错误。我已经在下面添加了模型类代码并获取了数据代码。请检查。
struct PlacesResult: Decodable {
let html_attributions: [String]?
let next_page_token: String?
let results : [Result]?
}
struct Result: Decodable {
let formatted_address: String?
let geometry: Geometry?
let icon: String?
let id: Int?
let name: String?
var photos: [Photos]?
let place_id: String?
let rating: String?
let types: [String]?
let user_ratings_total: Int?
}
struct Geometry: Decodable {
let location: Location?
let viewport: ViewPort?
}
struct Location: Decodable {
let lat: String?
let lng: String?
}
struct ViewPort: Decodable {
let northeast: NorthEast?
let southwest: SouthWest?
}
struct NorthEast: Decodable {
let lat: String?
let lng: String?
}
struct SouthWest: Decodable {
let lat: String?
let lng: String?
}
struct Photos: Decodable {
var height: Int?
var width: Int?
var photo_reference: String?
var html_attributions: [String]?
}
if let data = responseObject.dataObject as? Data {
do {
let placesData = try JSONDecoder().decode(PlacesResult.self, from: data)
print(placesData.next_page_token)
//print(placesData.results?.count)
}
catch {
print("Error : \(error.localizedDescription)")
}
}
错误:
错误:typeMismatch(Swift.String,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ results”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),CodingKeys(stringValue :“ geometry”,intValue:nil),CodingKeys(字符串值:“ location”,intValue:nil),CodingKeys(stringValue:“ lat”,intValue:nil)],debugDescription:“希望对String进行解码,但是找到了一个数字。 “,underlyingError:nil))
答案 0 :(得分:0)
添加的DecodingError
消息非常全面。它包含错误的类型,密钥路径和说明。
为弄清结构,这是分成多行的消息
Error : typeMismatch(Swift.String, Swift.DecodingError.Context(
codingPath:
[CodingKeys(stringValue: "results", intValue: nil),
_JSONKey(stringValue: "Index 0", intValue: 0),
CodingKeys(stringValue: "geometry", intValue: nil),
CodingKeys(stringValue: "location", intValue: nil),
CodingKeys(stringValue: "lat", intValue: nil)],
debugDescription:
"Expected to decode String but found a number instead.", underlyingError: nil))
codingPath
描述了密钥路径。它指向键lat
(又名location
)数组的第一项中字典geometry
的字典中results
字典的键results[0].geometry.location.lat
(又名debugDescription
)< / li>
lat
描述了错误。 期望 是建议的错误类型, 找到 是实际类型。Double
的值不是字符串,而是一个数字,很可能是String
所有 JSON键和字符串值都用双引号引起来,因此可以立即识别guard let data = try? Data(contentsOf:fileUrl) else { return }
类型。