ios - swift 对象映射器 : How to parse array inside of an array

标签 ios json swift alamofire objectmapper

这是我的 JSON 响应:

[
    [
        {
            "id": 22,
            "request_id": "rqst5c12fc9e856ae1.06631647",
            "business_name": "Code Viable",
            "business_email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bbb7bcbd98aeb1b9bab4bdf6bbb7b5" rel="noreferrer noopener nofollow">[email protected]</a>",
            "title": "Apache Load/Ubuntu",
        }
    ],
    [
        {
            "id": 24,
            "request_id": "rqst5c130cae6f7609.41056231",
            "business_name": "Code Viable",
            "business_email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3c303b3a1f29363e3d333a713c3032" rel="noreferrer noopener nofollow">[email protected]</a>",
            "title": "Load",
        }
    ]
]

这个 JSON 结构在数组内部有一个数组,内部数组的对象就是我要解析的对象。这是我的映射器:

struct JobResponseDataObject: Mappable {

    init?(map: Map) {

    }

    var id: Int?
    var requestId: String?
    var businessName: String?
    var businessEmail: String?

    mutating func mapping(map: Map) {

        id              <- map["id"]
        requestId       <- map["request_id"]
        businessName    <- map["business_name"]
        businessEmail   <- map["business_email"]

    }
}

我尝试创建另一个映射器struct来保存对象数组[JobResponseDataObject]并使用Alamofire的responseArray,但它不起作用。我还尝试在我的 json id 前添加 0. 前缀,但这也不起作用。请帮忙

谢谢

最佳答案

事情是这样的……Codable 是 Apple 提供的一个非常酷的协议(protocol),用于处理 API 的 JSON 响应解析。您返回的是一个数组数组,因此您的内容将如下所示:

[[ResponseObject]]

所以无论如何,你都会创建一个对象的结构,如下所示:

struct ResponseObject: Codable {
    let id: Int?
    let requestId: String?
    let businessName: String?
    let businessEmail: String?
    let title: String?
}

您会注意到我稍微更改了 key 名称(我使用了 requestId,而不是 request_id)。原因是 JSONDecoder 有一个名为 keyDecodingStrategy 的属性,它提供了可供您选择的预设解码策略的枚举。你会做convertFromSnakeCase

这是您可以转储到 Playground 中进行修改的代码。基本上,声明您的结构,将其与 JSON 中的任何键相匹配,声明一个解码器,为其提供解码策略,然后对其进行解码。

以下是进行 Alamofire 调用的方法:

    private let backgroundThread = DispatchQueue(label: "background",
                                                 qos: .userInitiated,
                                                 attributes: .concurrent,
                                                 autoreleaseFrequency: .inherit,
                                                 target: nil)


    Alamofire.request(url).responseJSON(queue: backgroundThread) { (response) in
        guard response.result.error == nil else {
            print("💥KABOOM!💥")
            return
        }

        if let data = response.data {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase

            do {
                let parsedResponse = try decoder.decode([[ResponseObject]].self, from: data)
                print(parsedResponse)
            } catch {
                print(error.localizedDescription)
            }
        }
    }

这是您可以在 Playground 上使用的代码。

import UIKit

let json = """
[
    [
        {
        "id": 22,
        "request_id": "rqst5c12fc9e856ae1.06631647",
        "business_name": "Code Viable",
        "business_email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfef2f9f8ddebf4fcfff1f8b3fef2f0" rel="noreferrer noopener nofollow">[email protected]</a>",
        "title": "Apache Load/Ubuntu",
        }
    ],
    [
        {
        "id": 24,
        "request_id": "rqst5c130cae6f7609.41056231",
        "business_name": "Code Viable",
        "business_email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a59555e5f7a4c535b58565f14595557" rel="noreferrer noopener nofollow">[email protected]</a>",
        "title": "Load",
        }
    ]
]
"""

struct ResponseObject: Codable {
    let id: Int?
    let requestId: String?
    let businessName: String?
    let businessEmail: String?
    let title: String?
}

if let data = json.data(using: .utf8) {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase

    do {
        let parsedResponse = try decoder.decode([[ResponseObject]].self, from: data)
        print(parsedResponse)
    } catch {
        print(error.localizedDescription)
    }
}

关于ios - swift 对象映射器 : How to parse array inside of an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789481/

相关文章:

ios - 动态计算单元格高度

javascript - 如何在 JavaScript 中将普通日期转换为 JSON 日期?

javascript - Rails 5 - 以 json 格式将数据从 Controller 发送到 javascript

ios - 使用 on/off 开关来摆脱不同 View Controller 中的 UILabel

ios - 为什么 CIContext.createCGImage 会导致内存泄漏?

objective-c - NSInvalidArgumentException 未被代码捕获

objective-c - NSlogging 和 NSString 难题

Python Flask 解析输出中的 JSON 内容

Swift - 按下按钮(完成处理程序问题)

ios - 如何在iOS中获取默认的系统颜色?