gpt4 book ai didi

ios - 解码错误 : The data couldn't be read. Alamofire

转载 作者:搜寻专家 更新时间:2023-11-01 06:28:16 24 4
gpt4 key购买 nike

我试图通过 JSONDecoder 解析 JSON 并使用 Alamofire 获取数据。但是,当我运行该应用程序时,它显示由于格式不正确而无法读取数据。我尝试了很多东西,但仍然没有用。任何帮助,将不胜感激。来源如下:

风投:

class SecondTaskVC: UIViewController {

var weatherModel = [WeatherModelDecodable]()

override func viewDidLoad() {
let url = URL(string: "https://api.openweathermap.org/data/2.5/forecast?lat=42.874722&lon=74.612222&APPID=079587841f01c6b277a82c1c7788a6c3")

Alamofire.request(url!).responseJSON { (response) in

let result = response.data

do{
let decoder = JSONDecoder()
self.weatherModel = try decoder.decode([WeatherModelDecodable].self, from: result!) // it shows this line as a problem

for weather in self.weatherModel {
print(weather.city.name)
}
}catch let error{
print("error in decoding",error.localizedDescription)

}

}
}
}

数据模型:

struct WeatherModelDecodable: Decodable {
let city: CityDecodable
}

struct CityDecodable: Decodable {
let name: String
}

最佳答案

实际上响应结构与你在这一行试图做的不同,

self.weatherModel = try decoder.decode([WeatherModelDecodable].self, from: result!)

响应不是一个数组,正如您在 json viewer 中看到的那样通过在任何浏览器中点击此 Url。您期待一个 json 对象数组,但它不是。因此,如果您将其解码为单个对象,它将正确解码,如下所示,

let weatherModel = try decoder.decode(WeatherModelDecodable.self, from: result!)
print(weatherModel.city.name)

因此,SecondTaskVC 将如下所示,

class SecondTaskVC: UIViewController {

var weatherModel: WeatherModelDecodable?

override func viewDidLoad() {
let url = URL(string: "https://api.openweathermap.org/data/2.5/forecast?lat=42.874722&lon=74.612222&APPID=079587841f01c6b277a82c1c7788a6c3")

Alamofire.request(url!).responseJSON { (response) in

let result = response.data

do{
let decoder = JSONDecoder()
self.weatherModel = try decoder.decode(WeatherModelDecodable.self, from: result!)
print(self.weatherModel!.city.name)
}catch let error{
print("error in decoding",error.localizedDescription)

}

}
}
}

您应该使用在响应中获得的相同结构解码相应的对象。

enter image description here

关于ios - 解码错误 : The data couldn't be read. Alamofire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51021823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com