Custom converter for Retrofit 2

JCarlosR picture JCarlosR · Feb 19, 2016 · Viewed 37.5k times · Source

I have to handle a dynamic JSON responses.

Before, I was using classes and annotations as follows:

public class ChatResponse {

    @SerializedName("status")
    private int status;

    @SerializedName("error")
    private String error;

    @SerializedName("response")
    private Talk response;

    public int getStatus() {
        return status;
    }

    public String getError() {
        return error;
    }

    public Talk getResponse() {
        return response;
    }
}

When the status is 1 (success) the onResponse is fired and I can get a ChatResponse object. But, when the status is 0, the response is false in the JSON representation and it fails (onFailure is fired).

I want to create my custom converter, and this question has a good example, but that example is for Retrofit 1.

I have to create a class that extends Converter.Factory, but I don't know how to override the methods of this class.

Actually I have the next:

@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {

    return super.fromResponseBody(type, annotations);
}

@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {

    return super.toRequestBody(type, annotations);
}

How I can parse the JSON response by my own at this point?

Thanks in advance.

Answer

JCarlosR picture JCarlosR · Feb 20, 2016

I was looking for a simple example about how to implement a custom converter for Retrofit 2. Unfortunately found none.

I found this example but, at least for me, it's too complicated for my purpose.

Happilly, I found a solution.

This solution is to use GSON deserializers.

We don't need to create a custom converter, we just have to customize the GSON converter.

Here is a great tutorial. And here is the code I used to parse the JSON described in my question:

  • Login Deserializer: Defines how to parse the JSON as an object of our target class (using conditionals and whatever we need).

  • Custom GSON converter: Builds a GSON converter that uses our custom deserializer.