KeyDecodingStrategy .convertFromSnakeCase不起作用

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

我有一个名为ServiceHealthApi的适配器类,它具有此功能:

final class ServiceHealthApi {
    let mockApi = "https://staging.myapp.com/health"

    func getHealth() -> Single<ServiceHealthResponseModel> {
        let url = URL(string: mockApi)
        guard let validUrl = url else { return .never() }

        var urlRequest = URLRequest(url: validUrl)
        urlRequest.httpMethod = "GET"
        let headers = [
            "Content-Type" : "application/json; charset=utf-8"
        ]
        urlRequest.allHTTPHeaderFields = headers
        return URLSession.shared.rx.data(request: urlRequest)
            .take(1)
            .map {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                return try JSONDecoder().decode(ServiceHealthResponseModel.self, from: $0) }
            .asSingle()

    }
}

struct HealthResponseModel: Decodable {
    struct DataResponse: Decodable {
        let serviceName: String
        let serviceStatus: String
        let serviceOperational: Bool
    }

    struct Meta: Decodable {
        let statusCode: Int
        let statusMessage: String
    }

    let data: [DataResponse]
    let meta: Meta
}

应该被解析的JSON字符串如下:

{
    "data": [
        {
            "service_name": "web",
            "service_status": "UP",
            "service_operational": true
        },
        {
            "service_name": "orm",
            "service_status": "UP",
            "service_operational": true
        }
    ],
    "meta": {
        "status_code": 200,
        "status_message": "OK"
    }
}

现在,当我尝试运行集成测试时,由于JSONDecoder中的此错误而失败:

错误keyNotFound(CodingKeys(stringValue:“ serviceName”,intValue:nil),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ data”,intValue:无),_ JSONKey(stringValue:“索引0”,intValue:0)],debugDescription:“没有与键关联的值CodingKeys(stringValue:\“ serviceName \”,intValue:nil)(\“ serviceName \”)。“,underlyingError:nil))]

[有趣的是,如果我禁用了.convertFromSnakeCase,并且仅使用驼峰式作为响应模型中的变量名称,它就可以正常工作。我知道我可能可以使用编码键,但是我只是想知道,为什么我的实现无法正常工作?

提前感谢。

PS:我尝试直接解析JSON字符串而不调用API,它确实起作用。

ios json swift rx-swift decodable
1个回答
0
投票

您正在创建没有任何策略的第二个JSONDecoder

© www.soinside.com 2019 - 2024. All rights reserved.