简体   繁体   中英

Swift parse json from API - The data couldn’t be read because it isn’t in the correct format

I get this error when fetching json data from API. I did some research on the site, but still could not solve the problem. How can I solve this problem?

JSON Data

date    :   2020.09.29
time    :   17:48:25
violence  : 3.2
region: AKDENIZ
struct EarthQuake: Codable {

    var date: String
    var time: String
    var violence: Double
    var region: String
}
 func fetchPostData(completionHandler: @escaping ([EarthQuake]) -> Void) {

        let url = URL(string: "https://test.xyz.php")!

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

            guard let data = data else { return }
            do {
                let postsData = try JSONDecoder().decode([EarthQuake].self, from: data)

                completionHandler(postsData)

            } catch {
                let error = error
                print(error.localizedDescription)
            }
        }.resume()

    }

It might be worth double checking the response object from the api you're calling and making sure that it adheres to the type [EarthQuake].self. (Which should be a list of EarthQuake objects). If the JSON data you added in your original post is the correct data returned from the endpoint then that is not a list and if it is an EarthQuake object you just will need to remove the brackets. so

[EarthQuake].self. should be EarthQuake.self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM