简体   繁体   中英

I am trying to parse JSON from a subreddit with Swift Codable. Why are my objects returning nil?

I am parsing JSON from a subreddit in Swift. The URL is: " https://www.reddit.com/r/swift/.json " The objects are returning nil and keyNotFound . I feel like perhaps my nesting is incorrect or something with the network call. Is it my Model or NetworkingService ? Thanks!

My Reddit Model looks like this:

import Foundation

struct Model : Decodable {
    let data: Children
}

struct Children: Decodable {
    let children: [RedditData]
}

struct RedditData: Decodable {
    let data: SecondaryData
}

struct SecondaryData : Decodable {
    let selftext: String
    let preview: Images
}

struct Images: Decodable {
    let images: [Source]
}

struct Source: Decodable {
    let url: URL
}

My NetworkingService looks like this:

import Foundation

class NetworkingService {

    static let shared = NetworkingService()
    private init() {}

    let session = URLSession.shared

    func getReddits(success successBlock: @escaping (Model) -> Void) {
        guard let url = URL(string: "https://www.reddit.com/r/swift/.json") else { return }
        let request = URLRequest(url: url)

        session.dataTask(with: request) { [weak self] data, _, error in
            guard self != nil else { return }

            if let error = error { print(error); return }
            do {
                let decoder = JSONDecoder()
                //decoder.keyDecodingStrategy = .convertFromSnakeCase

                let model = try decoder.decode(Model.self, from: data!)
                successBlock(model)
                print("model is \(model)")
            } catch {
                print(error)
            }
            }.resume()
    }
}

Error being thrown:

keyNotFound(CodingKeys(stringValue: "url", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "data", intValue: nil), CodingKeys(stringValue: "preview", intValue: nil), CodingKeys(stringValue: "images", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"url\", intValue: nil) (\"url\").", underlyingError: nil))
2019-08-02 06:13:59.068781-0400 Testing[65504:3994601] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9814c0dc70] get output frames failed, state 8196
2019-08-02 06:13:59.068978-0400 Testing[65504:3994601] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9814c0dc70] get output frames failed, state 8196
2019-08-02 06:13:59.069779-0400 Testing[65504:3994601] TIC Read Status [1:0x0]: 1:57
2019-08-02 06:13:59.069899-0400 Testing[65504:3994601] TIC Read Status [1:0x0]: 1:57

You are missing the source property of the JSON

struct Images: Decodable {
    let images: [Image]
}

struct Image: Decodable {
    let source: Source
}

struct Source: Decodable {
    let url: URL
    let width: Int
    let height: Int
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM