Home > Enterprise >  Decoding JSON with struct returns nil
Decoding JSON with struct returns nil

Time:10-31

I am trying to learn requests to an API. I am using News API to test. I have two structs and a WebService function.

I have no idea what could be wrong here, as I am following a tutorial to learn this, and doing exactly what the teacher is showing me to do.

Struct:

import Foundation

struct ArticleList: Decodable {
    let status: String
    let articles: [Article]
}

struct Article: Decodable { // Decodable because we only read, we do not send anything with this struct
    let title: String
    let description: String
}

Here is the WebService:

import Foundation

class Webservice {
    
    func getArticles(url: URL, completion: @escaping ([Article]?) -> ()) {
        
        print("URL: \(url)")
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print(error.localizedDescription)
                completion(nil)
            } else if let data = data {
                
                let articleList = try? JSONDecoder().decode(ArticleList.self, from: data)
            
                
                if let articleList = articleList {
                    completion(articleList.articles)
                }
                
                print(articleList?.articles)
            }
        }.resume()
        
    }
    
}

The last print in the WebService class is printing nil even though I am using the News API link: https://newsapi.org/v2/top-headlines?country=us&apiKey=XX and yes I am using an apiKey instead of XX and when I visit the link, I get the json so that should not be the problem.

What am I doing wrong here?

CodePudding user response:

Never use

try?

It is ignoring errors, use

do{
    //Your code here
}catch{
    print(error)
}

CodingKeys(stringValue: "description", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil)) is telling you that it found null therefore...

Change let description: String to let description: String?

To make it optional, the API will not always have a value for the description.

Errors should always be handled gracefully. You should identify a way to throw or return a Result with a failure.

The user should be told if there is an issue.

  • Related