Alamofire 的 responseJSON 和 responseData 的区别

Jin*_*ian 4 alamofire

我只是在玩 Alamofire 框架并进行很少的 api 调用。但是我观察到 alamofire 中有两种请求方法

Alamofire 的 responseJSON 和 responseData 有什么区别。

public func responseData(
    queue: DispatchQueue? = nil,
    completionHandler: @escaping (DataResponse<Data>) -> Void)
    -> Self
{
    return response(
        queue: queue,
        responseSerializer: DataRequest.dataResponseSerializer(),
        completionHandler: completionHandler
    )
}




public func responseJSON(
    queue: DispatchQueue? = nil,
    options: JSONSerialization.ReadingOptions = .allowFragments,
    completionHandler: @escaping (DataResponse<Any>) -> Void)
    -> Self
{
    return response(
        queue: queue,
        responseSerializer: DataRequest.jsonResponseSerializer(options: options),
        completionHandler: completionHandler
    )
}
Run Code Online (Sandbox Code Playgroud)

Fog*_*ter 8

responseJSON将传递一个 JSON 对象到它的完成中。即它将是一个带有String键和 JSON 兼容值的字典或数组。

responseData将一个Data对象传递给它的完成。这可能包含可以反序列化为 JSON 对象的 JSON 数据,但它也可能包含任何其他类型的数据。图像数据、HTML、视频数据等...

如果您知道您正在从端点获取 JSON,请使用该responseJSON调用。

  • @prettyitgirl.com 如果数据不是有效的 json,那么您将收到该错误。如果响应中是 json,则仅使用 responseJSON。如果不是,您可以使用 responseData ,它只会将原始数据传递给您(例如,它可能是文件或其他类型的数据)。 (2认同)