Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

android - Custom converter for Retrofit 2

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...