Retrofit 2.0 How to Get Deserialised Error Response.Body

Retrofit 2.0 how to get deserialised error response.body

solved it by:

Converter<MyError> converter = 
(Converter<MyError>)JacksonConverterFactory.create().get(MyError.class);
MyError myError = converter.fromBody(response.errorBody());

Retrofit2 Deserialize response body even if response is not 200

Retrofit is doing the serialization part by delegating it to the Converter, you you can add a specific one to the builder by using builder.addConverterFactory(GsonConverterFactory.create())
and there is already many written Retrofit Converters, you can find most of them here.

so if you want to control this process of deserialization, you can write your custom converter, something like this

public class UnwrapConverterFactory extends Converter.Factory {

private GsonConverterFactory factory;

public UnwrapConverterFactory(GsonConverterFactory factory) {
this.factory = factory;
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(final Type type,
Annotation[] annotations, Retrofit retrofit) {
// e.g. WrappedResponse<Person>
Type wrappedType = new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
// -> WrappedResponse<type>
return new Type[] {type};
}

@Override
public Type getOwnerType() {
return null;
}

@Override
public Type getRawType() {
return WrappedResponse.class;
}
};
Converter<ResponseBody, ?> gsonConverter = factory
.responseBodyConverter(wrappedType, annotations, retrofit);
return new WrappedResponseBodyConverter(gsonConverter);
}
}

then you use addConverterFactory() again to tell Retrofit about the new converter.
I should mention that you can use multiple converters in Retrofit which is awesome, it simply check converters by order till find the proper one to use.

resources: writing custom Retrofit converter, using multiple converters

Getting json from retrofit's response errorBody

You are using toString() in GSON's fromJson which is not a JSON content. Replace your toString() as string() which will give you the JSON body.
Also make sure to use the string() method only once and save the response in a variable, because it will return empty string if you used it again.

Not getting proper response of error body using retrofit

So, you are trying to getJSONObject from "user_msg" which is not possible because "user_msg" is not a JSONObject, it is a String.

A JSONObject would looks like:

"user_msg": {
"message": "Your error"
}

But that is not the case, you are getting two different String values.

"user_msg": "message",
"message" : "another message"

What you should do is jObjError.getString("user_msg") to get the value from "user_msg", and another jObjError.getString("message") to get the value from "message".



Related Topics



Leave a reply



Submit