为什么我的JSON解析无法在Swift中工作?

问题描述

我尝试了许多不同的解析方法,这是最好的方法,但是当我实际解析JSON时,我遇到了“错误解析”。我还添加了用于解析它的结构。该API是newsapi,我不知道为什么解析不起作用

struct NewsFeed: Codable {

    let status: String
    let totalResults: Int
    let articles: [Article]
}
    
struct Article: Codable {

    let source: [String:String]
    let author: String
    let title: String
    let description: String
    let url: String
    let urlToImage: String
    let content: String

}




private func getData(from url: String,label: UILabel) {
    
    
    URLSession.shared.dataTask(with: URL(string: url)!,completionHandler: {data,response,error in
        guard let data = data,error == nil else {
            print("Something went wrong")
            return
        }
        var results: NewsFeed?
        do {
            results = try JSONDecoder().decode(NewsFeed.self,from: data)
        }
        catch {
           print("Error parsing")
        }
        guard let json = results else {
            return
        }
            
        print(json.articles[0].content)
        label.text = json.articles[0].source["name"]
   
        
    }).resume()
}

解决方法

NewsAPI提供的JSON中的某些字段看起来可以为空。在这种情况下,使用可编码解码JSON时,必须指定可选属性。

此外,source属性是一个对象,因此我创建了一个对象,以使codable也知道如何解析它。

此示例似乎有效!

import Foundation

struct Newsfeed: Codable {
    let status: String
    let totalResults: Int
    let articles: [Article]
}

struct Article: Codable {
    let source: Source
    let author: String?
    let title: String
    let description: String?
    let url: URL?
    let urlToImage: URL?
    let content: String?
}

struct Source: Codable {
    let id: String?
    let name: String
}


private func getData(from url: String) {

    URLSession.shared.dataTask(with: URL(string: url)!,completionHandler: {data,response,error in
        guard let data = data,error == nil else {
            print("Something went wrong")
            return
        }
        var results: Newsfeed?
        do {
            results = try JSONDecoder().decode(Newsfeed.self,from: data)
        }
        catch {
            print("Error parsing \(error)")
        }
        guard let json = results else {
            return
        }

        print(json.articles[0].content)

    }).resume()
}

let apiKey = "YOUR_API_KEY"
let urlString = "http://newsapi.org/v2/top-headlines?country=us&apiKey=\(apiKey)"
getData(from: urlString)