Home > Net >  How do I load a remote JSON file in Swift?
How do I load a remote JSON file in Swift?

Time:12-14

I'm pretty much a complete beginner to Swift. I've played around with SwiftUI a bit, but that's about it. Needless to say, I have no idea how classes, structs, protocols, and everything else works in Swift.

I'm currently trying to figure out how to load a JSON file into Swift, and I cannot for the life of me get it to work. I would think that such a thing would be fairly rudimentary for such a modern language, but apparently not. After trying multiple tutorials and examples, I've come up with this messy code:

public class JSONReader {
    struct DatabaseObject: Decodable {
        let name: String
        let books: AnyObject
        let memoryVerses: AnyObject
    }
    private func parse(jsonData: Data) {
        do {
            let decodedData = try JSONDecoder().decode(DatabaseObject.self, from: jsonData)
            print(decodedData)
        } catch {
            print("decode error")
        }
    }
    private func loadJson(fromURLString urlString: String,
                          completion: @escaping (Result<Data, Error>) -> Void) {
        if let url = URL(string: urlString) {
            let urlSession = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
                if let error = error {
                    completion(.failure(error))
                }
                
                if let data = data {
                    completion(.success(data))
                }
            }
            urlSession.resume()
        }
    }
    init() {
        loadJson(fromURLString: "Redacted for privacy") { result in
            switch result {
                case .success(let data):
                    self.parse(jsonData: data)
                case .failure(let error):
                    print(error)
            }
        }
    }
}

I keep getting the buildtime error Type 'JSONReader.DatabaseObject' does not conform to protocol 'Decodable'

Any help, pointers, or tips would be greatly appreciated!

CodePudding user response:

The type AnyObject is not decodable by swift , The books property you are trying to decode and memoryVerse are not decodable , If you want to Decode this you can define their types separately as codable structs like so

struct Book : Codable{
    let property : String
    let otherProperty : String
}
struct Memory : Codable{
        let property : String
        let otherProperty : String
    }

struct DatabaseObject: Decodable {
        let name: String
        let books: Book
        let memoryVerses:Memory
    }
  • Related