ios - 如何在 iOS Swift 中使用 alamofire 获取 json 响应?
问题描述
我一直在尝试使用 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)
}
任何帮助非常感谢...
解决方案
您的模型类应如下所示。
import Foundation
public struct Filter: Codable {
let id: String
let name: String
let properties: Properties
}
public struct Properties: Codable {
let variables: [variables]
let color: String
let showUndefinedVariable: Bool
let description: String
let refresh: Bool
let priority: Int
}
public struct variables: Codable {
let name: String
let label: String
}
推荐阅读
- java - JTextField 输入异常检查和输入返回的问题
- reactjs - 当我从 API 获取数据时,MUI-dataTables 出错
- sql - 前 5 条记录,合并来自同一个表的两个查询
- javascript - 无法读取未定义的属性“_textureAtlas”
- go - 通过 websocket 使用 golang 提供 mp3 文件
- sql - Oracle为动态SQL创建公式以防止被零除
- qt - 圆角矩形的脏角不光滑
- amazon-web-services - AWS 警报表达式指标触发 ECS Auto Scale 策略时间 + cpu 利用率未触发
- sql - 选择字段以在访问中创建查询,会自动将星号 * 添加到所选字段。它显示在 SQL 视图中,但不显示在查询设计中
- google-sheets - Googlesheets中一个或多个单元格连续更改时的时间戳