使用Swift 4中的Decodable从嵌套JSON创建列表
我已经能够使用Swift 4的Decodable将JSON转换为结构,不幸的是,我无法使用名为“list”的JSON键将JSON转换为结构,这是一个包含其他结构的列表([])使用Swift 4中的Decodable从嵌套JSON创建列表,json,swift,struct,swift4,decodable,Json,Swift,Struct,Swift4,Decodable,我已经能够使用Swift 4的Decodable将JSON转换为结构,不幸的是,我无法使用名为“list”的JSON键将JSON转换为结构,这是一个包含其他结构的列表([]) { "cod":"200", "message":0.0061, "cnt":5, "list":[ { "dt":1522605600, "main":{ }, "weather":[ ], "clouds":{ }, "wind":{ },
{
"cod":"200",
"message":0.0061,
"cnt":5,
"list":[
{
"dt":1522605600,
"main":{ },
"weather":[ ],
"clouds":{ },
"wind":{ },
"rain":{ },
"sys":{ },
"dt_txt":"2018-04-01 18:00:00"
},
{
"dt":1522616400,
"main":{ },
"weather":[ ],
"clouds":{ },
"wind":{ },
"rain":{ },
"sys":{ },
"dt_txt":"2018-04-01 21:00:00"
},
{
"dt":1522627200,
"main":{
"temp":277.21,
"temp_min":277.21,
"temp_max":277.506,
"pressure":1016.3,
"sea_level":1023.98,
"grnd_level":1016.3,
"humidity":84,
"temp_kf":-0.3
},
这些是我的结构,我的方法是使ForecastInstance成为一个整体容器,其中包含一个属性“list”(如JSON),该属性属于ForecastList类型(包含嵌套结构)
在视图控制器中执行以下操作时,它会失败
self.currentForecast=try
JSONDecoder().decode(forecastingstance.self,from:data!)
任何帮助都将不胜感激。您的顶级结构需要如下所示,以模拟您的JSON结构。如果仍然出现错误,那么其余的结构看起来不错,我建议您也重新查看这些结构
struct ForecastInstance : Decodable {
let cod: String?
let message: Int?
let cnt: Int?
let list: [ForecastList]?
}
这是我的错误
debugDescription:“解析的JSON编号不符合Int.”,underyingError:nil))
将Int类型的属性压力更改为float成功了。它在操场上工作!
下面是一篇关于Codable的好文章:
.
我希望这会有帮助
let weatherJSON = """
{
"list": [{
"dt": 1522605600,
"main": {
"temp": 30,
"humidity": 50,
"pressure": 40
},
"weather": ["cloudly"],
"clouds": {},
"wind": {},
"rain": {},
"sys": {},
"dt_txt": "2018-04-01 18:00:00"
}]
}
""".data(using: .utf8)!
struct Main: Codable {
let temp: Int?
let humidity: Int?
let pressure: Int?
}
struct Weather: Codable {
let dt: Int?
let main: Main?
let weather: [String]?
}
struct WeatherList: Codable {
let list: [Weather]?
}
let weather = try JSONDecoder().decode(WeatherList.self, from: weatherJSON)
let count = "\(weather.list?.count ?? 0)"
print(count)
请在发布前验证您的问题格式是否正确。问题是什么?你会得到什么错误?当我尝试填充结构时失败-self.currentForecast=try JSONDecoder().decode(forecastingstance.self,from:data!)再次:你会得到什么错误?发布所有试图解码你显示的JSON的代码,以及你得到的具体错误。抱歉,消息看起来像浮点或双精度,我把INT放错了,一般来说。我认为这不是解决问题的办法
let weatherJSON = """
{
"list": [{
"dt": 1522605600,
"main": {
"temp": 30,
"humidity": 50,
"pressure": 40
},
"weather": ["cloudly"],
"clouds": {},
"wind": {},
"rain": {},
"sys": {},
"dt_txt": "2018-04-01 18:00:00"
}]
}
""".data(using: .utf8)!
struct Main: Codable {
let temp: Int?
let humidity: Int?
let pressure: Int?
}
struct Weather: Codable {
let dt: Int?
let main: Main?
let weather: [String]?
}
struct WeatherList: Codable {
let list: [Weather]?
}
let weather = try JSONDecoder().decode(WeatherList.self, from: weatherJSON)
let count = "\(weather.list?.count ?? 0)"
print(count)