如何将 Alamofire 中的数据与 Codable 对象映射到特定字段?

问题描述 投票:0回答:2

对于我的 APIManager.swift

APIManager.manager.request(urlEncoded, method: useMethod, parameters: params, encoding: requestEncoding, headers: headers)
    .validate(statusCode: 200..<300)
    .responseJSON { response in
    switch response.result {
    case .success(let json):
        ///
    case .failure(let error):
        ///
    }
}

还有我的 API JSON 响应

{
    "code": 200,
    "status": "success",
    "response_data": {
        "name": "testing"
    }
}

我的模型

struct TesterModel: Codable {
    var name: String
}

我需要使用可编码协议映射对象,但仅映射到 API 响应中的

reponse_data
字段。如何从
.responseJSON
映射它?

json swift alamofire decodable
2个回答
1
投票

您可以对特定字段使用“CodingKeys”

enum CodingKeys

像这样:

struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    var location: Coordinate
    var vantagePoints: [Coordinate]
    
    enum CodingKeys: String, CodingKey {
        case name = "title"
        case foundingYear = "founding_date"
        
        case location
        case vantagePoints
    }
}

也可以使用 JSONDecoder() 进行解码

guard let response = try? JSONDecoder().decode(Landmark, data) else { return nil }

在此处查看更多内容Apple 文档


0
投票

您可以像这样创建另一个模型:

struct APIResponse: Codable {
    var code: Int
    var status: String
    var responseData: TesterModel
}

struct TesterModel: Codable {
    var name: String
}

然后你就可以这样做:

APIManager.manager.request(urlEncoded, method: useMethod, parameters: params, encoding: requestEncoding, headers: headers)
            .validate(statusCode: 200..<300)
            .responseJSON { response in
            switch response.result {
                guard let data = response.data else {
                    return
                }
                do {
                    let result = try JSONDecoder().decode(APIResponse.self, from: data)
                }
                catch {
                    
                }
        }
© www.soinside.com 2019 - 2024. All rights reserved.