Home > Blockchain >  How to fix coding keys error with JSON conversion
How to fix coding keys error with JSON conversion

Time:10-15

I have an API call that has a ViewModel that takes in an API and transfers the data into an Array. I keep on getting an error with the conversion to JSON.

ViewModel:

class ViewModel: ObservableObject {
    @Published var courses: [Course] = []
    
    func fetch() {
        guard let url = URL(string: "https://api.spaceflightnewsapi.net/v3/articles") else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { [weak self]data, _, error in
            guard let data = data, error == nil else {
                return
            }
            
            // Convert to JSON
            do {
                let courses = try JSONDecoder().decode([Course].self, from: data)
                DispatchQueue.main.async {
                    self?.courses = courses
                }
            } catch {
                print(error) //---Error Here---
                print("Error with converting to JSON")
            }
        }
        task.resume()
    }
}

Course is defined as:

struct Course: Hashable, Codable {
    let name: String
    let image: String
    let id: Int
    let title: String
    let newsSite: String
    let summary: String
    let publishedAt: String
    let updatedAt: String
    let featured: Bool
    let launches: String
    let events: String
}

I then get the error:

keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "name", intValue: nil) ("name").", underlyingError: nil))

Have I forgot to do something inside of the Course struct?

CodePudding user response:

...to fix coding keys error with JSON conversion, try this exapme code, that is, your models structs need to match the json data.

There is no name, and no image in the json data, also launches and events are not String.

struct Course: Identifiable, Hashable, Codable {
    let id: Int
    let title: String
    let url: String // <-- here
    let imageUrl: String // <-- here
    let newsSite, summary, publishedAt, updatedAt: String
    let featured: Bool
    let launches: [Launch]?  // <-- here
    let events: [Event]? // <-- here
}

struct Event: Identifiable, Hashable, Codable {
    let id: Int
    let provider: String
}

struct Launch: Identifiable, Hashable, Codable {
    let id, provider: String
}

Note, you will need to consult the docs to determine which properties are optional. In that case add ? to it.

  • Related