gpt4 book ai didi

json - swift 3 中的 ResponseCollectionSerializable

转载 作者:行者123 更新时间:2023-11-28 08:18:19 29 4
gpt4 key购买 nike

我是 Swift 的新手,无法弄清楚如何将 JSON 数组反序列化为 Swift 对象数组。我能够很好地将单个 JSON 用户反序列化为 Swift channel 对象,但不确定如何使用 JSON channel 数组执行此操作。

我的 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

最佳答案

此答案以 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
}
}

关于json - swift 3 中的 ResponseCollectionSerializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41965166/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com