Alamofire嵌套JSON Serializer

时间:2015-02-12 23:52:15

标签: json swift alamofire

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

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

第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)

            })
    }

}

1 个答案:

答案 0 :(得分:4)

解析逻辑肯定存在一些问题(主要是安全性)。我尽可能地重新创建了你的场景,并重新设计了看似有问题的部分。我已经设法修复你的解析,我很确定这个问题。从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从服务器返回请求后将触发的所有内容。问题是,我实际上无法调用您的服务器,而您没有提供必要的凭据或URL来实际调用它。如果您希望我进一步调试,我将需要该信息。尽管我已对PostCommentAuthor类所做的所有更改已解决您的问题,但我几乎是肯定的。

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

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