首页 > 解决方案 > 如何在 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)
   }

任何帮助非常感谢...

标签: iosjsonswiftalamofirecodable

解决方案


您的模型类应如下所示。

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

}

推荐阅读