Search code examples
alamofire

the difference between responseJSON and responseData of Alamofire


I was just playing with Alamofire framework and making few api calls. However I observed there are two request methods in alamofire

What is the difference between responseJSON and responseData of Alamofire.

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
    )
}

Solution

  • responseJSON will pass a JSON object into its completion. i.e. it will be a dictionary or array with String keys and JSON compatible values.

    responseData will pass a Data object into its completion. This may contain JSON data which can be deserialized into a JSON object but it also may contain any other type of data. Image data, HTML, video data, etc...

    If you KNOW that you are getting JSON from an endpoint then use the responseJSON call.