【发布时间】:2020-03-10 04:27:48
【问题描述】:
我一直在尝试使用 alamofire 从 url 获取 json 响应。创建模型、apirouter 和 api 客户端类。
显示错误
failure(Alamofire.AFError.responseSerializationFailed(reason:
Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error:
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "variables", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"variables\", intValue: nil) (\"variables\").", underlyingError: nil)))))
这是我的邮递员 json 回复:
[
{
"id": "00602c70-fc8a-11e9-ad1d-2abe2670111d",
"resourceType": "Task",
"name": "My Tasks",
"owner": null,
"query": {
"assigneeExpression": "${currentUser()}",
"taskVariables": [],
"processVariables": [],
"caseInstanceVariables": [],
"orQueries": []
},
"properties": {
"variables": [
{
"name": "loanAmount",
"label": "Loan Amount"
},
{
"name": "firstName",
"label": "First Name"
}
],
"color": "#555555",
"showUndefinedVariable": false,
"description": "Tasks assigned to me",
"refresh": false,
"priority": -10
}
}
]
我尝试从 json 响应中获取 id、name 和 properties -> variables -> name 和 label 的值。
这里是模型类:
import Foundation
public struct Filter: Codable {
let id: String
let name: String
let properties: [variables]
}
public struct variables: Codable {
let name: String
let label: String
}
这是 alamofire 的代码:
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (AFResult<T>)->Void) -> DataRequest {
return AF.request(route)
.responseDecodable (decoder: decoder){ (response: AFDataResponse<T>) in
completion(response.result)
print("framework response::",response.result)
}
}
public static func getFilter(completion:@escaping (AFResult<[Filter]>)->Void) {
let jsonDecoder = JSONDecoder()
performRequest(route: APIRouter.getFilter, decoder: jsonDecoder, completion: completion)
}
任何帮助都非常感谢...
【问题讨论】:
-
在访问
"variables"之前,您的 JSON 中缺少步骤"properties"。要么使用自定义初始化,要么使用 Properties 之间的结构。 -
最初我也有属性,但同样的错误来了..
-
提示:当 JSON Codable/Encodable 出现问题时,执行相反的操作,您将看到 JSON 期望您的代码,并可以与您的代码进行比较:pastebin.com/TREcv2zF(基于初始代码)
标签: ios json swift alamofire codable