我正在从事一个涉及地震的项目, 我用这个震级为4.5或更大的URL进行了呼叫,并且正确解码了数据。我在控制台上看到了响应:https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson
问题出在我使用另一个URL:https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.geojson时。该URL返回与上述URL相同的属性,但无法正确解码。
我尝试过的事情:
这就是我的模型:
struct Earthquake: Codable {
let type: String?
let metadata: Metadata?
let features: [Feature]
let bbox: [Double]?
}
// MARK: - Metadata
struct Metadata: Codable {
let generated: Int
let url: String
let title: String
let status: Int
let api: String
let count: Int
}
// MARK: - Feature
struct Feature: Codable {
let type: String
let properties: Properties
let geometry: Geometry
let id: String?
}
// MARK: - Properties
struct Properties: Codable {
let mag: Double?
let place: String?
let time, updated: Int?
let tz: Int?
let url: String?
let detail: String?
let felt: Int?
let cdi, mmi: Double?
let alert: String?
let status: String?
let tsunami, sig: Int?
let net: String?
let code, ids: String?
let sources: String?
let types: String?
let nst: Int?
let dmin: Double?
let rms: Double
let gap: Int?
let magType: String?
let type: String?
let title: String?
}
// MARK: - Geometry
struct Geometry: Codable {
let type: String
let coordinates: [Double]
}
这就是我所说的。
let topEarthQuakesURL = URL(string: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.geojson")!
let task = URLSession.shared.dataTask(with: topEarthQuakesURL) { (data, response, error) in
guard let data = data else {return}
print(data)
let decoder = JSONDecoder()
let EarthquakeData = try! decoder.decode(Earthquake.self, from: data)
print(EarthquakeData.features[0].geometry.coordinates)
}
task.resume()
我收到此错误。请注意,它已打印出1064216 bytes
。这告诉我我正在获取数据,但它只是在某一时刻无法正确解码。只是不确定在哪里。
1064216 bytes
Fatal error: 'try!' expression unexpectedly raised an error:
Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath:
[CodingKeys(stringValue: "features", intValue: nil), _JSONKey(stringValue: "Index 29", intValue:
29), CodingKeys(stringValue: "properties", intValue: nil), CodingKeys(stringValue: "gap",
intValue: nil)], debugDescription: "Parsed JSON number <231.67> does not fit in Int.",
underlyingError: nil)): file
/Users/olerma/Documents/EarthQuakes/Urth/Urth/Controller/MainViewController.swift, line 33
答案 0 :(得分:1)
properties-> gap -----解析的JSON数字<231.67>不适合Int。
所以改变
let gap: Int?
到
let gap: Double?