【发布时间】:2020-05-21 18:30:31
【问题描述】:
我正在从国家气象局获取天气预报。我得到了一个大致像这样的 JSON 对象(出于所有意图和目的):
{
"properties":{
"periods":[
{
"number":1,
"name":"This Afternoon",
"startTime":"2020-05-21T12:00:00-06:00",
"endTime":"2020-05-21T18:00:00-06:00",
"isDaytime":true,
"temperature":58,
"temperatureUnit":"F",
"temperatureTrend":"falling",
"windSpeed":"20 to 23 mph",
"windDirection":"SW",
"icon":"https://api.weather.gov/icons/land/day/rain,20",
"shortForecast":"Slight Chance Light Rain",
"detailedForecast":"A slight chance of rain. Partly sunny..."
},
{
"number":2,
"name":"Tonight",
"startTime":"2020-05-21T18:00:00-06:00",
"endTime":"2020-05-22T06:00:00-06:00",
"isDaytime":false,
"temperature":39,
"temperatureUnit":"F",
"temperatureTrend":"rising",
"windSpeed":"7 to 20 mph",
"windDirection":"S",
"icon":"https://api.weather.gov/icons/land/night/rain,50/rain,80",
"shortForecast":"Rain",
"detailedForecast":"Rain. Mostly cloudy..."
}
]
}
}
我已经定义了一个 Swift 结构来存储预测:
struct WeatherForecast {
var startTime : Date?
var endTime : Date?
var temperature : Int? // Degrees Fahrenheit.
var temperatureTrend : String?
var windSpeed : String? // Miles per hour
var windDirection : String?
var shortForecast : String?
var detailedForecast : String?
var iconPath : String?
}
如何解码“周期”部分,以便获得一组 WeatherForecast(又名 [WeatherForecast])?
【问题讨论】:
-
最简单的方法是在链上定义可解码的数据类型:一个包含
properties键,另一个用于periods键,例如struct Period: Decodable { let periods: [WeatherForecast] }。不要忘记让WeatherForecast可解码 -
@NewDev 我犯了一个错误-应该只有一个“句点”属性,它的值是一个数组。
-
好的 - 我编辑了你的问题来解决。但我所说的仍然存在