Alamofire 嵌套 JSON 序列化器

Posted

技术标签:

【中文标题】Alamofire 嵌套 JSON 序列化器【英文标题】:Alamofire Nested JSON Serializer 【发布时间】:2015-02-12 23:52:14 【问题描述】:

我正在使用 Alamofire 向 JSON API 发出请求。我正在尝试序列化 Post 对象的集合,其中包含一个作者对象和一个 cmets 数组。

Click to see the hosted JSON

我做了以下事情:

第 1 步:按照步骤操作

扩展Alamofire.Request 对象并添加ResponseObjectSerializerResponseCollectionSerializer,如Generic Response Object Serialization 下的文档中所述

第 2 步:添加以下模型

Post.swift

final class Post : ResponseObjectSerializable, ResponseCollectionSerializable 

    let id: Int
    let title: String
    let body: String
    let author: Author
    let comments: [Comment]

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        self.id = representation.valueForKeyPath("id") as Int
        self.body = representation.valueForKeyPath("body") as String
        self.title = representation.valueForKeyPath("title") as String

        // What do I do with the author object

        var authorObj: AnyObject? = representation.valueForKeyPath("author")

        if (authorObj != nil) 
            self.author = Author(response: response, representation: authorObj!)!
        

        // What do I do with the comments Array?
        self.comments = Comment.collection(response: response, representation: representation.valueForKeyPath("comments")!)

    

    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Post] 
        var postList:[Post] = []
        for p in representation as [AnyObject] 
            postList.append(Post(response: response, representation: p)!)
        
        return postList
    


Comment.swift

final class Comment : ResponseObjectSerializable, ResponseCollectionSerializable 

    let id: Int
    let body: String

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        self.id = representation.valueForKeyPath("id") as Int
        self.body = representation.valueForKeyPath("body") as String
    

    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Comment] 
        var commentList:[Comment] = []
        var commentArray = representation as [AnyObject]
        for c in commentArray 
            commentList.append(Comment(response: response, representation: c)!)
        
        return commentList
    


作者.swift

final class Author : ResponseObjectSerializable 

    let id: Int
    let name: String

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        self.id = representation.valueForKeyPath("id") as Int
        self.name = representation.valueForKeyPath("name") as String
    

第 3 步:表示是 Builtin.RawPointer

(lldb) po representation (instance_type = Builtin.RawPointer = 0x00007f8b9ae1d290 -> 0x000000010c7f4c88 (void *)0x000000010c7f4dc8: __NSArrayI)

有什么建议吗?

第 4 步:这是我调用代码的方式

class NetworkPostProvider 

    typealias RequestsCollectionResponse = (NSError?, [Post]?) -> Void

    class func all(onCompletion: RequestsCollectionResponse) 

        var manager = Alamofire.Manager.sharedInstance

        manager.session.configuration.HTTPAdditionalHeaders = [
            "Authorization": NSUserDefaults.standardUserDefaults().valueForKey(DEFAULTS_TOKEN) as String
        ]

        manager.request(.GET, BASE_URL + "/alamofire/nested")
            .validate()
            .responseCollection( (req, res, requests:[Post]?, error) -> Void in
                println("Request:")
                println(req)
                println("Response:")
                println(res)

                println(requests)

            )
    


【问题讨论】:

如果您发布您如何使用 Alamofire 调用它会有所帮助。 @cnoon 这有帮助吗? 【参考方案1】:

您的解析逻辑肯定存在一些问题(主要是安全性)。我尽我所能重新创建了你的场景,并重新设计了看起来有问题的部分。我已经设法修复了您的解析,我很确定这是问题所在。从 Alamofire 的角度来看,您似乎正确地调用了所有内容。

import Foundation
import Alamofire

@objc public protocol ResponseObjectSerializable 
    init?(response: NSHTTPURLResponse, representation: AnyObject)


@objc public protocol ResponseCollectionSerializable 
    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]


extension Alamofire.Request 
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self 
        let serializer: Serializer =  (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil 
                return (T(response: response!, representation: JSON!), nil)
             else 
                return (nil, serializationError)
            
        

        return response(serializer: serializer, completionHandler:  (request, response, object, error) in
            completionHandler(request, response, object as? T, error)
        )
    

    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self 
        let serializer: Serializer =  (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil 
                return (T.collection(response: response!, representation: JSON!), nil)
             else 
                return (nil, serializationError)
            
        

        return response(serializer: serializer, completionHandler:  (request, response, object, error) in
            completionHandler(request, response, object as? [T], error)
        )
    


final class Post : ResponseObjectSerializable, ResponseCollectionSerializable, Printable 

    let id: Int
    let title: String
    let body: String
    let author: Author
    let comments: [Comment]

    var description: String 
        return "Post id = \(self.id), title = \(self.title), body = \(self.body), author = \(self.author), comments = \(self.comments)"
    

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        let id = representation.valueForKeyPath("id") as? Int
        let title = representation.valueForKeyPath("title") as? String
        let body = representation.valueForKeyPath("body") as? String

        var author: Author?

        if let authorObject: AnyObject = representation.valueForKeyPath("author") 
            author = Author(response: response, representation: authorObject)
        

        var comments: [Comment]?

        if let commentsObject: AnyObject = representation.valueForKeyPath("comments") 
            comments = Comment.collection(response: response, representation: commentsObject)
        

        if id != nil && body != nil && title != nil && author != nil && comments != nil 
            self.id = id!
            self.title = title!
            self.body = body!
            self.author = author!
            self.comments = comments!
         else 
            self.id = 0
            self.title = ""
            self.body = ""
            self.author = Author(id: 0, name: "")
            self.comments = [Comment]()
            return nil
        
    

    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Post] 
        var postList = [Post]()

        for p in representation as [AnyObject] 
            if let post = Post(response: response, representation: p) 
                postList.append(post)
            
        

        return postList
    


final class Comment : ResponseObjectSerializable, ResponseCollectionSerializable, Printable 

    let id: Int
    let body: String

    var description: String 
        return "Comment id = \(self.id), name = \(self.body)"
    

    init(id: Int, body: String) 
        self.id = id
        self.body = body
    

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        let id = representation.valueForKeyPath("id") as? Int
        let body = representation.valueForKeyPath("body") as? String

        if id != nil && body != nil 
            self.id = id!
            self.body = body!
         else 
            self.id = 0
            self.body = ""
            return nil
        
    

    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Comment] 
        var commentList = [Comment]()
        var commentArray = representation as [AnyObject]

        for c in commentArray 
            if let comment = Comment(response: response, representation: c) 
                commentList.append(comment)
            
        

        return commentList
    



final class Author : ResponseObjectSerializable, Printable 

    let id: Int
    let name: String

    var description: String 
        return "Author id = \(self.id), name = \(self.name)"
    

    init(id: Int, name: String) 
        self.id = id
        self.name = name
    

    required init?(response: NSHTTPURLResponse, representation: AnyObject) 
        let id = representation.valueForKeyPath("id") as? Int
        let name = representation.valueForKeyPath("name") as? String

        if id != nil && name != nil 
            self.id = id!
            self.name = name!
         else 
            self.id = 0
            self.name = ""
            return nil
        
    


class NetworkPostProvider 

    typealias RequestsCollectionResponse = (NSError?, [Post]?) -> Void

    class func all(onCompletion: RequestsCollectionResponse) 

        var manager = Alamofire.Manager.sharedInstance

        manager.session.configuration.HTTPAdditionalHeaders = [
            "Authorization": NSUserDefaults.standardUserDefaults().valueForKey("12345678") as String
        ]

        let request = manager.request(.GET, "Some base url" + "/alamofire/nested")
        request.validate()
        request.responseCollection  (req, res, requests: [Post]?, error) in
            println("Request:")
            println(req)
            println("Response:")
            println(res)

            println(requests)
        
    

    class func forceLoadJSON() 
        let path = NSBundle.mainBundle().pathForResource("stacked", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) 
            println(json)
            let fakeResponse = NSHTTPURLResponse(URL: NSURL(string: "")!, statusCode: 200, HTTPVersion: nil, headerFields: nil)!
            let posts = Post.collection(response: fakeResponse, representation: json)
            println("Posts: \(posts)")
         else 
            println("Failed to load the posts")
        
    

forceloadJSON 方法重新创建一旦请求从服务器返回,Alamofire 将触发的所有内容。问题是我实际上不能调用你的服务器 b/c 你没有提供必要的凭据或 URL 来实际调用它。如果您希望我进一步调试它,我将需要该信息。尽管我对PostCommentAuthor 类所做的所有更改都已经解决了您的问题,但我几乎是肯定的。

我建议的另一个改变是使用结构而不是类。目前在 Swift 1.1 编译器中有一个 bug 不允许您在类内的可失败初始化程序中使用 return nil。这很可能在 Swift 1.2 中得到修复,但我还没有检查过。

我要更改的最后一件事是修改 ResponseCollectionSerializable 函数 collection 以便能够返回可选数组或可选数组。这是因为您的集合方法可能无法创建实例,因为它正在调用可失败的初始化程序。目前它正在掩埋这些错误,您不知道解析是否失败。你以前会在那种情况下崩溃(也许这就是你想要的)。我对其进行了修改,使其不会崩溃,但错误随后被掩埋。

【讨论】:

以上是关于Alamofire 嵌套 JSON 序列化器的主要内容,如果未能解决你的问题,请参考以下文章

json 使用 alamofire 快速发布嵌套对象

为我可以用来操作 JSON 的 Alamofire 创建回调

如何使用 Alamofire 发布嵌套的 JSON?

AlamoFire 4.0 + SwiftyJSON 展开深度嵌套的 JSON

如何使用 Alamofire 和 SwiftyJSON 访问嵌套的 JSON 值?

将 3 级嵌套 json 隐藏到 Alamofire 参数