【问题标题】:How to get json response using alamofire in iOS Swift?如何在 iOS Swift 中使用 alamofire 获取 json 响应?
【发布时间】: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


【解决方案1】:

您的模型类应如下所示。

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

}

【讨论】:

    【解决方案2】:

    你试过这个吗?应该是这样的

    public struct Filter: Codable {
        let id: String
        let name: String
        let properties: Property
    }
    
    public struct Property: Codable {
        let variables: [Variable]
    }
    
    public struct Variable: Codable {
        let name: String
        let label: String
    
    }
    

    【讨论】:

      【解决方案3】:

      您收到的错误消息非常清楚:No value associated with key CodingKeys(stringValue: \"variables\"

      您正在尝试将 JSON 解码为 Filter 结构,但 JSON 没有 variables 属性。您可以通过引入一个新的 Properties 结构来解决此问题,该结构将包装 variables 属性,如下所示:

      struct Filter: Codable {
          let id: String
          let name: String
          let properties: Properties
      }
      
      struct Properties: Codable {
          let variables: Variables
      }
      
      struct Variables: Codable {
          let name: String
          let label: String
      }
      

      此外,正如您将在此 sn-p 中看到的那样,约定以 CamelCase 编写类型名称,因此 struct Variables 而不是 struct variables

      【讨论】:

      • 仍然面临同样的错误失败(Alamofire.AFError.responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(错误:Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context (codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "properties", intValue: nil)], debugDescription: "期望解码 Array 但找到了字典。",基础错误:无)))))
      • 这不起作用,因为properties 不是一个数组,它是一个对象。仔细查看 JSON。
      猜你喜欢
      • 2015-03-11
      • 2014-11-15
      • 2020-12-02
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多