Java how to convert errorBody to pojo in retrofit

Java how to convert errorBody to pojo in retrofit

To convert an error body to a POJO (Plain Old Java Object) in Retrofit, you can use a custom Converter.Factory and the fromBody method of the Converter interface.

Here is an example of how you can create a custom Converter.Factory to convert an error body to a POJO in Retrofit:

public class ErrorConverterFactory extends Converter.Factory {
  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    if (type == ErrorResponse.class) {
      return new Converter<ResponseBody, ErrorResponse>() {
        @Override
        public ErrorResponse convert(ResponseBody value) throws IOException {
          return new Gson().fromJson(value.string(), ErrorResponse.class);
        }
      };
    }
    return null;
  }
}
So‮u‬rce:www.lautturi.com

This code defines a ErrorConverterFactory class that extends the Converter.Factory class and overrides the responseBodyConverter method. The responseBodyConverter method checks if the type is ErrorResponse, and if it is, it returns a Converter that uses the Gson library to parse the error body into an ErrorResponse object.

To use the ErrorConverterFactory, you will need to add it to the Retrofit object when you create it, like this:

Retrofit retrofit = new Retrofit.Builder()
  .baseUrl()
Created Time:2017-11-03 22:21:04  Author:lautturi