【发布时间】:2020-03-21 09:20:15
【问题描述】:
我有一个名为 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: 无),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue: “数据”,intValue:无),_JSONKey(stringValue:“索引0”,intValue: 0)], debugDescription: "没有与键关联的值 CodingKeys(stringValue: \"serviceName\", intValue: nil) (\"serviceName\").", 基础错误:nil))
有趣的是,如果我禁用了 .convertFromSnakeCase,并且只在响应模型中使用驼峰命名法作为变量名,它就可以正常工作。我知道我可能可以使用编码键,但我只是想知道,为什么我的实现不起作用?
提前致谢。
PS:我尝试直接解析JSON 字符串而不调用API,它确实有效。
【问题讨论】:
标签: ios json swift rx-swift decodable