我正在从Swift中的subreddit解析JSON。网址为:“ 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
答案 0 :(得分:1)
您缺少JSON的source属性
struct Images: Decodable {
let images: [Image]
}
struct Image: Decodable {
let source: Source
}
struct Source: Decodable {
let url: URL
let width: Int
let height: Int
}