Swift 4可编码阵列

时间:2017-08-29 00:07:10

标签: swift swift4 codable

所以我有一个返回JSON对象数组的API路由。例如:

[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]

我正在尝试设想如何在Swift中使用新的可编码特性将它们转换为类中的两个对象。因此,如果我有一个可编码的人类,我会想要采取这种反应并让它给我两个人物。

我也在使用Alamofire来处理请求。

我该怎么做?到目前为止,我所看到的与可编码内容有关的所有内容只允许1个对象。我还没有看到任何与Alamofire或网络框架的集成。

5 个答案:

答案 0 :(得分:16)

关于Alamofire 5的更新:responseJSONDecodable

struct Person: Codable {
    let firstName, lastName: String
    let age: Int

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
    }
}

Alamofire.request(request).responseJSONDecodable { (response: DataResponse<Person>) in
    print(response)
}

Alamofire 4目前尚未添加Codable支持(请参阅#2177),您可以改为使用此扩展程序:https://github.com/Otbivnoe/CodableAlamofire

let jsonData = """
[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]
""".data(using: .utf8)!

struct Person: Codable {
    let firstName, lastName: String
    let age: Int

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
    }
}

let decoded = try! JSONDecoder().decode([Person].self, from: jsonData)

示例:http://swift.sandbox.bluemix.net/#/repl/59a4b4fad129044611590820

使用CodableAlamofire:

let decoder = JSONDecoder()
Alamofire.request(url).responseDecodableObject(keyPath: nil, decoder: decoder) { (response: DataResponse<[Person]>) in
    let persons = response.result.value
    print(persons)
}

keypath对应于结果包含在JSON结构中的路径。 E.g:

{
    "result": {
        "persons": [
            {"firstname": "Tom", "lastname": "Smith", "age": 31},
            {"firstname": "Bob", "lastname": "Smith", "age": 28}
        ]
    }
}

keypath =&gt; results.persons

[
    {"firstname": "Tom", "lastname": "Smith", "age": 31},
    {"firstname": "Bob", "lastname": "Smith", "age": 28}
]

keypath =&gt; nil(空keypath抛出异常)

答案 1 :(得分:0)

我设法将数据响应序列化为可编码对象。

例如,您可能已熟悉转换json对象[String: String]。需要使用Data将该json对象转换为json.data(using: .utf8)!

使用Alamofire,很容易获得这些数据(或者至少这种数据对我有效,已经与.utf8兼容),我可以使用这个已经可用的功能

func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self

然后只使用该数据作为Decoder

completionHandler的输入
let objek = try JSONDecoder().decode(T.self, from: data)

你也可以通过文档

对一些通用的序列化函数进行一些调整

Generic Response Object Serialization

到这个修改

func responseCodable<T: Codable>(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<T>) -> Void)
    -> Self
{
    let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
        guard error == nil else { return .failure(BackendError.network(error: error!)) }

        guard let data = data else {
            return .failure(BackendError.objectSerialization(reason: "data is not valid"))
        }


        do{
            let objek = try JSONDecoder().decode(T.self, from: data!)
            return .success(objek)
        } catch let e {
            return .failure(BackendError.codableSerialization(error: e))
        }

    }

    return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}

示例结构

struct Fids: Codable {

   var Status: Status?
   var Airport: Airport?
   var Record: [FidsRecord]
}

以这种方式使用这个功能

    Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse<Fids>) in
        switch response.result{
        case .success(let value):
            print(value.Airport)
        // MARK: do whatever you want
        case .failure(let error):
            print(error)
            self.showToast(message: error.localizedDescription)
        }
    }

答案 2 :(得分:0)

要解码为数组,为了清楚起见,您将响应放在类型别名中:

localStorage

但随后您必须确认Array可编码:

typealias ServiceResponseObject = [ResponseObject]

这应该使所有工作正常。

答案 3 :(得分:0)

使用Codable快速5

Alamofire通用响应

PersonModel.swift (使用SwiftyJsonAccelerator创建)

import Foundation

class PersonModel: Codable {

  enum CodingKeys: String, CodingKey {
    case age
    case firstname
    case lastname   }

  var age: Int?   var firstname: String?   var lastname: String?

  init (age: Int?, firstname: String?, lastname: String?) {
    self.age = age
    self.firstname = firstname
    self.lastname = lastname   }

  required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    age = try container.decodeIfPresent(Int.self, forKey: .age)
    firstname = try container.decodeIfPresent(String.self, forKey: .firstname)
    lastname = try container.decodeIfPresent(String.self, forKey: .lastname)   }

}

通用获取响应

func genericGET<T: Decodable>(urlString: String, completion: @escaping (T?) -> ()) {

Alamofire.request(urlString)
    .responseJSON { response in
        // check for errors
        switch response.result {
        case .success(_):

            do {
                let obj = try JSONDecoder().decode(T.self, from: response.data!)
                completion(obj)
            } catch let jsonErr {
                print("Failed to decode json:", jsonErr)
            }

            break
        case .failure(_):


            completion(nil)

            break
        }
}

}

调用此方法

genericGET(urlString: "YOUR_URL") { (persons: [PersonModel]?) in
    print(persons?[0].firstname)
}

答案 4 :(得分:-2)

对于其他任何人,Swifts Codable Array Json都有问题,这意味着您的Json是否以[]而不是Json对象{}开头。

我的替代结果是:

struct PersonWrapperHelper: Codable {
    let data: [PersonWrapper]
}

struct PersonWrapper: Codable {
    let firstName: String
    let lastName: String
    let age: Int
}

...

var result = [PersonWrapper]()

if let data = data, // data = your request data (request JSON)
let personString = String(data: data, encoding: .utf8),
let stringToData = ("{ \"data\":" + personString + "}").data(using: .utf8),
let json = try? JSONDecoder().decode(PersonWrapperHelper.self, from: stringToData) {
    result = json.data
}

DispatchQueue.main.async {
    callBack(result) // return result
}