Alamofire 嵌套 JSON 序列化程序

Alamofire Nested JSON Serializer

我正在使用 Alamofire 向 JSON API 发出请求。我正在尝试序列化一个 Post 对象的集合,这些对象中有一个作者对象和一个注释数组。

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
    }

}

Author.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
    }
}

第三步:表示是一个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 的角度来看,您似乎正在正确调用所有内容。

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 class 所做的所有更改得到解决。

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

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