Alamofire + Decodable-如何将responseJSON转换为NSData

时间:2018-08-23 14:33:23

标签: alamofire swift4 decodable jsondecoder

我很确定我的问题很容易解决,但是找不到任何解决方案。 所以我有Alamofire的要求,并且在处理数据类型时遇到麻烦。我有很多“打印输出”只是为了检查我逐步得到的数据。

Alamofire.request(URL, method: .get, headers: headers).responseJSON { response in
            switch responseJSON.result {
            case .success(let value):
                print(type(of: value))  //__NSDictionaryI
                print(value)
                print(type(of:responseJSON))  //DataResponse<Any>
                print(responseJSON) . //SUCCESS: {"billing_addresses" =     (...
                print(responseJSON.value as Any) . //Optional({...
                //print(responseJSON.value as! [[String:Any]]) . //Could not cast value of type '__NSDictionaryI' (0x10b9fb508) to 'NSArray' (0x10b9fb008).

                do {
                    let decoder = JSONDecoder()
                    let model = try decoder.decode(Info.self, from: value as! Data) //Decode JSON Response Data
                    print(model.id)
                } catch let parsingError {
                    print("Error", parsingError)
                }

现在我有一个错误:**Could not cast value of type '__NSSingleEntryDictionaryI' (0x10d240f78) to 'NSData' (0x10d241090).**

responseJSON的值为:

(我不确定该值是否正确,因为当我签入Postman时,所有字符串都被双引号引起来,并且“ is_default”的值为true / false,而不是0/1。但是在Xcode中,我是已经在控制台中得到了。所以responseJSON可能有问题吗?..)

可能有零个地址,也可能有几个。

{
"id": 40128,
"username": "test6",
"email": "test6@on.com",
"billing_addresses": [
    {
        "address_name": null,
        "country_code": "US",
        "first_name": "Ted",
        "last_name": "Qqqq",
        "company_name": "",
        "address_line1": "308 Sea Lane",
        "address_line2": "",
        "city": "QQQQ",
        "state": "FL",
        "postcode": "32000",
        "email_address": "test6@on.com",
        "phone_number": "11111111",
        "is_default_for_billing": true
    }
],
"shipping_addresses": [
    {
        "address_name": null,
        "country_code": "US",
        "first_name": "Ted",
        "last_name": "Qqqq",
        "company_name": "",
        "address_line1": "308 Sea Lane",
        "address_line2": "",
        "city": "QQQQ",
        "state": "FL",
        "postcode": "32000",
        "is_default_for_shipping": true
    }
]

}

这是模特

struct Info : Decodable {
                    let id: Int
                    let email: String
                    let username: String
                    let billing_addresses: Billings
                    let shipping_addresses: Shippings
                }
                struct Billings: Decodable{
                    let address_name: String
                    let country_code: String
                    let first_name: String
                    let last_name: String
                    let company_name: String
                    let address_line1: String
                    let address_line2: String
                    let city: String
                    let state: String
                    let postcode: String
                    let email_address: String
                    let phone_number: String
                    let is_default_for_billing: Bool

                }
                struct Shippings:Decodable{
                    let address_name: String
                    let country_code: String
                    let first_name: String
                    let last_name: String
                    let company_name: String
                    let address_line1: String
                    let address_line2: String
                    let city: String
                    let state: String
                    let postcode: String
                    let is_default_for_shipping: Bool

                }

如果我尝试将SwiftyJSON与value作为参数一起使用,则会出现错误,提示Any不能为Data,我真的不知道该怎么办。

1 个答案:

答案 0 :(得分:2)

responseJSON.result.value返回反序列化的集合类型,在您的情况下为字典[String:Any]

要使用JSONDecoder,您需要response.data中的原始数据

let model = try decoder.decode(Info.self, from: response.data) //Decode JSON Response Data

考虑到您将遇到解码错误:billing_addressesshipping_addresses是数组

let billing_addresses: [Billings] 
let shipping_addresses: [Shippings] // better name both structs in singular form (Billing, Shipping)

,有些值可能是数字而不是字符串。

无论如何,建议使用convertFromSnakeCase密钥解码策略来摆脱难看的snake_case名称。

编辑:

这是带有驼峰名称和单数形式的结构,您必须添加

decoder.keyDecodingStrategy = .convertFromSnakeCase

struct Info : Decodable {
    let id: Int
    let email: String
    let username: String
    let billingAddresses: [Billing]
    let shippingAddresses: [Shipping]
}

struct Billing : Decodable {
    let addressName: String?
    let countryCode, firstName, lastName, companyName: String
    let addressLine1, addressLine2, city, state, postcode: String
    let emailAddress, phoneNumber: String
    let isDefaultForBilling: Bool

}
struct Shipping : Decodable {
    let addressName: String?
    let countryCode, firstName, lastName, companyName: String
    let addressLine1, addressLine2, city, state, postcode: String
    let isDefaultForShipping: Bool
}