[英]I am trying to parse JSON from the Swift subreddit. Why am I having issues?
[英]I am trying to parse JSON from a subreddit with Swift Codable. Why are my objects returning nil?
我正在從 Swift 的 subreddit 解析 JSON。 URL 是:“ https://www.reddit.com/r/swift/.json ” 對象返回nil
和keyNotFound
。 我覺得我的嵌套可能不正確或網絡調用有問題。 是我的Model
還是NetworkingService
? 謝謝!
我的 Reddit Model
如下所示:
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
您缺少 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.