解码错误:无法读取数据。 Alamofire

时间:2018-06-25 10:56:01

标签: ios swift xcode alamofire decoder

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

VC:

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
 }

1 个答案:

答案 0 :(得分:3)

实际上,响应结构与您在此行尝试执行的操作不同,

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

响应不是一个数组,您可以在json viewer中通过在任何浏览器中点击此网址来看到它。您期望一个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