swift-从Reddit API解码JSON响应(发布评论)

维罗妮卡·巴比(Veronika Babii)

我在JSON中从Reddit API(来自特定subreddit的一篇文章)中获得reddit发表评论,然后通过Structs解析JSON。当我尝试输出解码后的注释时,出现错误:

解码Json注释时出错-typeMismatch(Swift.Dictionary <Swift.String,Any>,Swift.DecodingError.Context(codingPath:[],debugDescription:“预期解码Dictionary <String,Any>但找到一个数组。”,underlyingError :无)

也许我在存储库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))

让我们解构一下:

您可以从中读到两个有用的信息:

首先,debugDescription:期望对Dictionary <String,Any>进行解码,但是找到了一个数组。

这意味着您正在尝试解码字典,但JSON包含一个数组。请注意,您标记为Codable的大多数普通类型都将编码为字典。

其次,,codingPath在您的情况下为空数组([]),这意味着此问题恰好在您尝试解码的根类型上。

现在,让我们看看您发布的Postman回复。在第1行中,您可以看到最外面的容器(第1行)是一个数组。

但是,在解码时,您正在解码的CommentListing是使用键控容器(字典)的。

因此,要解决此问题,您必须解码CommentListings的数组

let postsResponse = try JSONDecoder().decode([CommentListing].self, from: jsonData!)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章