I am using Retrofit 2.0.0-beta2 .
I found an example of converting a synchronous .errorBody to an object.
I need to execute it asynchronously.
This is my json:
{
"error_msg": "This user name is already registered."
}
When I run the asynchronous example, I get null .
package com.test.client;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.lang.annotation.Annotation;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Converter;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
import retrofit.http.GET;
public final class DeserializeErrorBody {
interface Service {
@GET("account.signup")
Call<User> getUser();
}
static class User {
}
static class Error {
String error_msg;
}
public static void main(String... args) throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.site.com/method/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Service service = retrofit.create(Service.class);
Call<User> response = service.getUser();
response.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response, Retrofit retrofit) {
if(!responce.isSuccess()) {
System.out.println(response.errorBody().string());
Converter<ResponseBody, Error> errorConverter = retrofit.responseConverter(Error.class, new Annotation[0]);
try {
Error error = errorConverter.convert(response.errorBody());
System.out.println(error);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Throwable t) {
}
});
}
}
Sorry for my bad english :)
In an asynchronous request, it successfully returns a string . However, conversion to an object is not performed .
How to get an object instead of null ?