尝试使用JSONDecoder(),但无法解析JSON

时间:2019-05-08 00:09:41

标签: ios json swift parsing jsondecoder

我正在尝试从newsapi.org解析一些JSON数据。我有一个JSONDecoder()

的模型班

我试图将JSON数据解析为的模型是:

struct ArticleService: Decodable {

    var totalResults:Int?
    var articles:[Articles]?
}
struct Articles: Decodable {

    var author:String?
    var title:String?
    var description:String?
    var url:String?
    var urlToImage:String?
    var publishedAt:Date?
    var content:String?
}

Decoder

protocol ArticleModelProtocol {

    func articlesRetrieved(_ articles: [Articles]) 
}

class ArticleModel {

    var delegate: ArticleModelProtocol?

func getArticles() {

    let urlString = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=018f69dd3e7f467996bb8bd648d7739e"
    let url = URL(string: urlString)

    guard url != nil else { return print("could not load url")}

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

        // If there are no errors and there is data
        if error == nil && data != nil {
            do {
                // Decode JSON data into Structs
                let result = try JSONDecoder().decode(ArticleService.self, from: data!)

                // Do this on the main thread
                DispatchQueue.main.async {
                    self.delegate?.articlesRetrieved(result.articles!)
                }
            }
            catch {
                print("Could not decode data. \(error)")
                return
            }
        }
    }
    dataTask.resume()
}
}

JSON

{
    "status": "ok",
    "totalResults": 10,
    -"articles": [
    -{
    -"source": {
    "id": "techcrunch",
    "name": "TechCrunch"
    },
    "author": "Kirsten Korosec",
    "title": "Waymo and Lyft partner to scale self-driving robotaxi service in Phoenix",
    "description": "Waymo is partnering with Lyft to bring self-driving vehicles onto the ride-hailing network in Phoenix as the company ramps up its commercial robotaxi service. Waymo will add 10 of its self-driving vehicles on Lyft platform over the next few months, according …",
    "url": "https://techcrunch.com/2019/05/07/waymo-and-lyft-partner-to-scale-self-driving-robotaxi-service-in-phoenix/",
    "urlToImage": "https://techcrunch.com/wp-content/uploads/2017/09/waymo_minivan_7.jpg?w=600",
    "publishedAt": "2019-05-07T20:42:20Z",
    "content": "Waymo is partnering with Lyft to bring self-driving vehicles onto the ride-hailing network in Phoenix as the company ramps up its commercial robotaxi service.\r\nWaymo will add 10 of its self-driving vehicles on Lyft platform over the next few months, according… [+1387 chars]"
}

当我在模型类中运行JSONDecoder()时,它捕获到一条错误消息:

  

typeMismatch(Swift.Double,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ articles”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),CodingKeys(stringValue:“ PublishedAt”,intValue:nil)],debugDescription:“预期对Double进行解码,但找到了一个字符串/数据。”,底层错误:nil))

想知道是否有人之前曾遇到此错误,或者可以给我一些见识?

0 个答案:

没有答案