Ios swift-解码来自RedditAPI的JSON响应(发表评论)
我从RedditAPI中获取一篇来自JSON中特定子reddit的文章的reddit post注释,然后通过结构解析JSON。当我试图输出解码的评论时,我得到一个错误: 解码Json注释时出错-typemistmatchswift.Dictionary, Swift.DecodingError.ContextcodingPath:[],调试说明: 应解码字典,但找到数组 相反,UnderlineError:nil 也许我在结构中遗漏了什么,或者在Repository getComments方法中遗漏了不匹配的类型。请给我一些建议Ios swift-解码来自RedditAPI的JSON响应(发表评论),ios,json,swift,api,reddit,Ios,Json,Swift,Api,Reddit,我从RedditAPI中获取一篇来自JSON中特定子reddit的文章的reddit post注释,然后通过结构解析JSON。当我试图输出解码的评论时,我得到一个错误: 解码Json注释时出错-typemistmatchswift.Dictionary, Swift.DecodingError.ContextcodingPath:[],调试说明: 应解码字典,但找到数组 相反,UnderlineError:nil 也许我在结构中遗漏了什么,或者在Repository getComments方法中
enum RequestURL {
case top(sub: String, limit: Int)
case postAt(sub: String, id: String)
var url: String {
switch self {
case .top(let sub, let limit):
return "https://www.reddit.com/r/\(sub)/top.json?limit=\(limit)"
case .postAt(let sub, let id):
return "https://www.reddit.com/r/\(sub)/comments/\(id).json"
}
}
}
class HTTPRequester {
init() {}
func getData (url: RequestURL, completion: @escaping(Data?) -> Void) {
guard let url = URL(string: url.url) else {
print("Error: Request URL is nil!")
completion(nil)
return
}
URLSession.shared.dataTask(with: url) {data,_,error in
guard let jsonData = data else {
print(error ?? "Error")
completion(nil)
return
}
completion(jsonData)
}.resume()
}
}
class Service {
init() {}
func decodeJSONComments(url: RequestURL, completion: (@escaping (_ data: CommentListing?) -> Void)) {
HTTPRequester().getData(url: url) { jsonData in
do {
let postsResponse = try JSONDecoder().decode(CommentListing.self, from: jsonData!)
print(postsResponse)
completion(postsResponse)
} catch {
print("Error decoding Json comments - \(error)")
completion(nil)
}
}
}
}
class Repository {
init() {}
func getComments(sub: String, postId: String, completion: (@escaping ([RedditComment]) -> Void)) {
Service().decodeJSONComments(url: RequestURL.postAt(sub: sub, id: postId)) { (comments: CommentListing?) in
var commentsList = [CommentData]()
commentsList = (comments?.data.children) ?? []
let mappedComs = commentsList.map { (comment) -> RedditComment in
return RedditComment(
id: comment.data.id,
author: comment.data.author,
score: comment.data.score,
body: comment.data.body)
}
completion(mappedComs)
}
}
}
class UseCase {
func createComments(sub: String, postId: String, completion: (@escaping (_ data: [RedditComment]) -> Void)) {
Repository().getComments(sub: sub, postId: postId) { (comments: [RedditComment]) in
completion(comments)
}
}
}
UseCase().createComments(sub: "ios", postId: "4s4adt") { comments in
print(comments)
}
JSON结构
尝试将您的响应解码为注释列表数组,如:
尝试将响应解码为注释列表数组,如:
您提到您有以下错误:
typeMismatch(Swift.Dictionary<String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
您提到您有以下错误:
typeMismatch(Swift.Dictionary<String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
非常感谢。这对我真的很有用!这对我很有用,因为你的回答和清楚的解释!!谢谢你的回答和清楚的解释!!
let postsResponse = try JSONDecoder().decode([CommentListing].self, from: jsonData!)