ios - JSON 可解码问题
问题描述
所以我试图在操场上使用 JSON Decodable 从 api 端点获取数据。我已按照步骤创建结构并使其符合Decodable
这样的要求。
import Foundation
struct Weather: Decodable {
let latitude: String
let longitude: String
let timezone: String
let offset: Int
let currently : Currently
init(latitude: String,longitude: String,timezone: String,offset: Int,currently : Currently) {
self.latitude = latitude
self.longitude = longitude
self.timezone = timezone
self.offset = offset
self.currently = currently
}
enum CodingKeys: String, CodingKey {
case currently = "currently",latitude = "latitude",longitude = "longitude",timezone = "timezone", offset = "offset"
}
}
struct Currently: Decodable {
let time: Int
let summary: String
let icon: String
let precipIntensity: Double
let precipProbability: Int
let precipType: String
let temperature: Double
let apparentTemperature: Double
let dewPoint: Double
let humidity: Double
let pressure: Double
let windSpeed: Double
let windGust: Double
let windBearing: Double
let cloudCover: Double
let uvIndex: Double
let visibility: Double
init(time: Int,summary: String,icon: String,precipIntensity: Double,precipProbability: Int, precipType: String,temperature: Double,apparentTemperature: Double,dewPoint: Double, humidity: Double,pressure: Double,windSpeed: Double, windGust: Double,windBearing: Double,cloudCover: Double,uvIndex: Double,visibility: Double) {
self.time = time
self.summary = summary
self.icon = icon
self.precipIntensity = precipIntensity
self.precipProbability = precipProbability
self.precipType = precipType
self.temperature = temperature
self.apparentTemperature = apparentTemperature
self.dewPoint = dewPoint
self.humidity = humidity
self.pressure = pressure
self.windSpeed = windSpeed
self.windGust = windGust
self.windBearing = windBearing
self.cloudCover = cloudCover
self.uvIndex = uvIndex
self.visibility = visibility
}
enum CodingKeys : Any, CodingKey {
case time,summary,icon,precipIntensity,precipProbability,precipType,temperature,apparentTemperature,
dewPoint,humidity,pressure,windSpeed,windGust,windBearing,cloudCover,uvIndex,visibility
}
}
但是当我尝试 URLSession 并获取数据时,我得到了这个错误
keyNotFound(CodingKeys(stringValue: "当前", intValue: nil)
我不确定我做错了什么我将我的对象建模为类似于将链接输入浏览器时 json 响应的外观。
{
"latitude":42.3601,
"longitude":-71.0589,
"timezone":"America/New_York",
"currently":{
"time":255657600,
"summary":"Heavy Snow and Dangerously Windy",
"icon":"snow",
"precipIntensity":0.1692,
"precipProbability":1,
"precipType":"snow",
"temperature":30.38,
"apparentTemperature":13.49,
"dewPoint":29.24,
"humidity":0.95,
"pressure":1006.67,
"windSpeed":40.36,
"windGust":83.48,
"windBearing":63,
"cloudCover":1,
"uvIndex":0,
"visibility":0.2
},
"offset":-5
}
我已经包含了 JSON 结构,以便更好地阐明我的方向。谁能看到我哪里出错了?
获取api数据的代码也在下面
@objc func fetchWeatherData(location: String, time: Date){
LocationService.getEventLocation(address: location) { (place) in
guard let places = place else {
return
}
for place in places {
print(place.coordinates?.latitude as Any)
print(place.coordinates?.longitude as Any)
let jsonURLString = "https://api.darksky.net/forecast/d455ebdd2abdcb5160adc4e70919367c/\(place.coordinates?.latitude ?? 0),\(place.coordinates?.longitude ?? 0),\(time.timeIntervalSince1970)?exclude=minutely,flags,hourly,daily,alerts"
print(jsonURLString)
guard let url = URL(string: jsonURLString) else {
return
}
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, err) in
guard let data = data else {
return
}
do {
let weather = try JSONDecoder().decode(Weather.self, from: data)
print(weather)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}).resume()
}
}
}
解决方案
其实你应该得到
预期解码字符串,但找到了一个数字。codingPath: [CodingKeys(stringValue: "latitude", intValue: nil)]
因为latitude
和longitude
是Double
(没有双引号)。
顺便说一句,您的结构不需要初始化程序,也不需要CodingKeys
,这就足够了:
struct Weather: Decodable {
let latitude, longitude: Double // must be Double not String
let timezone: String
let offset: Int
let currently : Currently
}
struct Currently : Decodable {
let time: Int
let summary, icon: String
let precipIntensity: Double
let precipProbability: Double // must be Double not Int
let precipType: String
let temperature, apparentTemperature: Double
let dewPoint, humidity, pressure, windSpeed: Double
let windGust, windBearing, cloudCover, uvIndex, visibility: Double
}
推荐阅读
- html - Firefox 中的动画问题
- graph - 在 Y 轴上着色范围
- c# - 在已创建的 TCP 套接字上使用 Webclient
- angular - 如何根据用户点击角度显示数据
- apache-kafka - 对两个不同的环境使用相同的 kafka 主题
- puma - 为什么在部署后找不到我的数字海洋空间的 Rails 凭据?
- merge - 合并在日期上匹配的查询,如果未找到匹配项则保留 null
- php - ErrorException:试图获取非对象的属性“max_score”
- java - 花花公子进入 RecycleView 的 Android 应用程序
- html - 如果部分中没有值,则显示“无评论”