【问题标题】:handle two diffrent http json response swift快速处理两个不同的http json响应
【发布时间】:2020-02-15 09:34:06
【问题描述】:

我有一个 API 可以给我两种不同的响应。

这是数据正确且我有对象的时候:

{ "latlng": [My Objects] }

这是我的数据为空的时候:

[]

所以我的问题是当我使用 jsonDecoder 时如何处理这个空响应?

我的网络功能:

 func performNetworkingTaskWithParams<T: Codable>(endpoint: EndPointType, type: T.Type, params: [String : String],completion: ((_ response: T)-> Void)?) {
    let url = endpoint.baseURL.appendingPathComponent(endpoint.path)

    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept" : "application/json",
        "Content-Type" : "application/x-www-form-urlencoded"
    ]

    var urlRequest = URLRequest(url: url)

    let session = URLSession(configuration: config)

    urlRequest.encodeParameters(parameters: params)

    let taskSession = session.dataTask(with: urlRequest) { (data, response, error) in
        if let myError = error {
            print("request error:\(myError)")
            return
        }

        guard let responseData = data else {
            print("response is null!")
            return
        }


        let response = Response(data: responseData)

        guard let decoded = response.decode(type) else {
            print("cannot decode data!")
            return
        }
        completion?(decoded)
    }

    taskSession.resume()
}

【问题讨论】:

    标签: ios swift nsurlsession jsondecoder


    【解决方案1】:

    在您的codable 结构中,您应该实现自定义初始化并将您的数据设置为可选

    
    init(from decoder: Decoder) throws {
         let values = try decoder.container(keyedBy: CodingKeys.self)
         YourField = try? values.decode(TypeOFField.self, forKey: .yourfiled)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2014-02-25
      • 1970-01-01
      相关资源
      最近更新 更多