swift 3中的ResponseCollectionSerializable
Posted
技术标签:
【中文标题】swift 3中的ResponseCollectionSerializable【英文标题】:ResponseCollectionSerializable in swift 3 【发布时间】:2017-01-31 18:43:30 【问题描述】:我是 Swift 新手,无法弄清楚如何将 JSON 数组反序列化为 Swift 对象数组。我能够将单个 JSON 用户反序列化为 Swift 通道对象,但只是不确定如何使用 JSON 通道数组来实现。
我的 ResponseCollectionSerializable.swift
import Foundation
import Alamofire
public protocol ResponseObjectSerializable
init?(response: HTTPURLResponse, representation: AnyObject)
extension Request
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self
let responseSerializer = DataResponseSerializer<T, NSError> request, response, data, error in
guard error == nil else return .Failure(error!)
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result
case .Success(let value):
if let
response = response,
let responseObject = T(response: response, representation: value)
return .Success(responseObject)
else
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
case .Failure(let error):
return .Failure(error)
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
public protocol ResponseCollectionSerializable
static func collection(response: HTTPURLResponse, representation: AnyObject) -> [Self]
extension Alamofire.Request
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self
let responseSerializer = DataResponseSerializer<[T], NSError> request, response, data, error in
guard error == nil else return .Failure(error!)
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONSerializer.serializeResponse(request, response, data, error)
switch result
case .Success(let value):
if let response = response
return .Success(T.collection(response: response, representation: value))
else
let failureReason = "Response collection could not be serialized due to nil response"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
case .Failure(let error):
return .Failure(error)
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
我有一个问题: 使用未声明的类型“响应” 泛型类型“DataResponseSerializer”专用于太多类型参数(有 2 个但预期为 1 个)
enter image description here
我的模特:
import Foundation
import ObjectMapper
import SwiftyJSON
class AllCnannelModel : ResponseObjectSerializable, ResponseCollectionSerializable
var id : Int
var name: String
var url : String
var picture : String
var category_id: Int
public required init?(response: HTTPURLResponse, representation: AnyObject)
self.id = representation["id"] as! Int
self.name = representation["name"] as! String
self.url = representation["url"] as! String
self.picture = representation["picture"] as! String
self.category_id = representation["category_id"] as! Int
class func collection(response: HTTPURLResponse, representation: AnyObject) -> [AllCnannelModel]
let postArray = representation as! [AnyObject]
return postArray.map( AllCnannelModel(response:response, representation: $0)! )
问题:
enter image description here
【问题讨论】:
【参考方案1】:此答案以 the approach that the SwiftyJSON GitHub readme recommends 开头,用于从 Alamofire 响应构建 SwiftyJSON 对象。该问题不包括下面显示的Alamofire.request()
调用的等效项。这消除了对问题中某些方法的需求。
Alamofire.request("(put the URL here)", method: .get).validate().responseJSON response in
switch response.result
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
if let array = json.array
var channelArray: [AllCnannelModel] = []
for item in array
guard let dictionary = item.dictionaryObject else
continue
if let channel = AllCnannelModel(representation: dictionary)
channelArray.append(channel)
// Do something with channelArray
case .failure(let error):
print(error)
AllCnannelModel
初始化程序已修改为接受字典 [String: Any]
。
class AllCnannelModel
var id : Int
var name: String
var url : String
var picture : String
var category_id: Int
public required init?(representation: [String: Any])
self.id = representation["id"] as! Int
self.name = representation["name"] as! String
self.url = representation["url"] as! String
self.picture = representation["picture"] as! String
self.category_id = representation["category_id"] as! Int
【讨论】:
以上是关于swift 3中的ResponseCollectionSerializable的主要内容,如果未能解决你的问题,请参考以下文章
swift 3中的ResponseCollectionSerializable
Swift 3 中的 managedObjectContext