首页 > 解决方案 > 弹出JSON解码错误,不知道还有什么可以尝试的

问题描述

伙计们,我真的很感谢 JSON 解码方面的帮助。我正在尝试从此链接获取 API: http: //newsapi.org/v2/top-headlines ?apiKey=a16b15f863454928804e218705d0f019+&country=us 我可能犯了一些非常业余的错误。第一次在这里上传问题。求救!

这是我的数据管理器

protocol NewsManagerDelegate {
    func didUpdateNews(news: NewsModel)
}
import Foundation

struct NewsManager{
    
    
    var delegate: NewsManagerDelegate?
    
    let url = "https://newsapi.org/v2/top-headlines?apiKey=a16b15f863454928804e218705d0f019"
    
    
    func fetchNews(_ countryName: String){
        let newsUrlString = "\(url)+&country=\(countryName)"
        performRequest(newsUrlString)
    }
    
    func performRequest(_ urlString: String){
        if let url = URL(string: urlString){
            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print("networking error \(error!)")
                    return
                }
                
                if let safeData = data{
                    if let news = parseJSON(safeData){
                        delegate?.didUpdateNews(news: news)
                }
            }
            }
            task.resume()
        }
    }
    
    func parseJSON(_ newsData: Data) -> NewsModel?{
        do{
            let decodedData = try JSONDecoder().decode(NewsData.self, from: newsData)
            let sourceName = decodedData.articles[5].source.name
            let titleName = decodedData.articles[5].title
            let linkToImage = decodedData.articles[5].urlToImage
            let news = NewsModel(sourceName: sourceName, titleName: titleName, linkToImage: linkToImage ) 
            return news
        }catch{
            print(error)
            return nil
        }
        
    }
    
    
    
    
    
}

和我的数据

import Foundation

struct NewsData: Codable {
    let totalResults: Int
    let articles: [Articles]

}

struct Articles: Codable{
    let author: String?
    let title: String
    let description: String
    let urlToImage: String
    let source: Source
    
}

struct Source: Codable{
    let name: String
}

我收到此错误

valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "description", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))

我试图使一些常量成为可选的,但在那之后根本不会显示任何信息。

标签: iosjsonswift

解决方案


它说第一个值没有价值,你能发布你得到的 json 响应,因为这会很有用。另一种可能性可能是 json 响应的顺序与您正在解码的顺序不同。

您可以将描述更改为可选项,因为这样可以解决问题,但是您将没有描述,因此不能完全解决问题

let description: String?

推荐阅读