gpt4 book ai didi

ios - Alamofire 对象映射器 : how to parse nested array in swift

转载 作者:行者123 更新时间:2023-11-28 05:48:38 24 4
gpt4 key购买 nike

这是我的 api 响应:

[
[
{
"id": 24,
"request_id": "rqst5c130cae6f7609.41056231",
"business_name": "Code Viable",
"business_email": "code@viable.com",
"title": "Load",
"details": "load",
"load_description": "load",
"amount_offered": "1",
"pickup_address": "load",
"dropoff_address": "load",
"timestamp": "2018-12-14 01:51:42"
}
],
[
{
"id": 27,
"request_id": "rqst5c1325881836d2.98441728",
"business_name": "Code Viable",
"business_email": "code@viable.com",
"title": "Load",
"details": "brendan",
"load_description": "test load for brendan",
"amount_offered": "1222",
"pickup_address": "Load",
"dropoff_address": "Load",
"timestamp": "2018-12-14 03:37:44"
}
]
]

如您所见,它是一个包裹在数组内部的数组,我已经为内部数组设置了一个对象映射器,如下所示:

struct JobResponseDataObject: Mappable {

init?(map: Map) {

}

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

var title: String?
var details: String?
var loadDescription: String?
var amountOffered: String?

var pickUpAddress: String?
var dropOffAddress: String?
var timestamp: String?

mutating func mapping(map: Map) {

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

title <- map["title"]
details <- map["details"]
loadDescription <- map["load_description"]
amountOffered <- map["amount_offered"]

pickUpAddress <- map["pickup_address"]
dropOffAddress <- map["dropoff_address"]
timestamp <- map["timestamp"]
}
}

如果父级为其子级数组命名,那么我将为顶层创建另一个映射器。但在这种情况下,外部数组没有名称,我需要做什么才能使 alamofire .responseArray 调用正常工作?

Alamofire.request(JOB_REQUEST_BASE_URL, method: .post, parameters: parameter, encoding: URLEncoding(), headers: nil).responseArray { (response: DataResponse<[JobResponseDataObject]>) in


}
}

谢谢

最佳答案

您的 JSON 对象具有嵌套数组。因此,要解析它,您可以通过两种方式进行。一种方法是将其解析为嵌套数组。

DataResponse<[[JobResponseDataObject]]>

您的代码将如下所示。

Alamofire.request(JOB_REQUEST_BASE_URL, method: .post, parameters: parameter, encoding: URLEncoding(), headers: nil).responseArray { (response: DataResponse<[JobResponseDataObject]>) in

//...

}

建议:目前我从JSON中了解到的,不应该是嵌套的Array。如果你只需要在嵌套数组中添加一个对象,你可以用简单的数组来实现。

第二种方式如果嵌套数组中只有一个对象。您也可以按如下方式解析它。

requestId       <- map["0.request_id"]

“0”。在这里获取内部数组的第一个对象。希望这会有所帮助:)

关于ios - Alamofire 对象映射器 : how to parse nested array in swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773707/

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