首页 > 解决方案 > 我正在尝试使用 Swift Codable 从 subreddit 解析 JSON。为什么我的对象返回零?

问题描述

我正在从 Swift 的 subreddit 中解析 JSON。URL 是:“ https://www.reddit.com/r/swift/.json ”对象正在返回nilkeyNotFound. 我觉得也许我的嵌套不正确或网络调用有问题。是我的Model还是NetworkingService?谢谢!

我的 RedditModel看起来像这样:

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
}

我的 NetworkingService 如下所示:

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()
    }
}

抛出错误:

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

标签: iosswiftnetworkingcodable

解决方案


您缺少 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
}

推荐阅读