Renzo Renzo - 3 months ago 42
JSON Question

Why response.body() its null?

Im using retrofit to send a a json object to the server, im trying to create a user, im sending this json object


In this example i create a invalid user , so the server response with a json object where code its the code error and message its the explication of the error

[{"code":"5","message":"The email is in use"}]


public interface UserClient {

Call<Usuarios> create(@Body Usuarios usuario);


Data model

public class Usuarios {

String username;
String email;
String password;
String nombre;
String apellido;
String fechaDeNacimiento;
String formaDeRegistro;

String message;

public Usuarios(String email, String username, String password, String nombre, String apellido, String fechaDeNacimiento, String formaDeRegistro){
this.nombre = nombre;
this.apellido= apellido;
this.fechaDeNacimiento = fechaDeNacimiento;
this.formaDeRegistro = formaDeRegistro;

public String getMessage(){
return message;


and Retrofit implement

OkHttpClient.Builder okhttpClientBuilder=new OkHttpClient.Builder();
HttpLoggingInterceptor loggin=new HttpLoggingInterceptor();
Retrofit.Builder builder = new Retrofit.Builder()

Retrofit retrofit =;

UserClient service = retrofit.create(UserClient.class);
Call<Usuarios> call = service.create(usuario);

call.enqueue(new Callback<Usuarios>() {
public void onResponse(Call<Usuarios> call, Response<Usuarios> response) {

Toast.makeText(Main2Activity.this,"Usuario Registrado! "+response.body().getMessage,Toast.LENGTH_SHORT).show();


public void onFailure(Call<Usuarios> call, Throwable t) {
Toast.makeText(Main2Activity.this,"Algo fallo..",Toast.LENGTH_SHORT).show();


So i can see the logcat response but in the body its appoint to null, how i can acces to the "message"?

This is the logcat

Answer Source

That error is because your response is not successful therefore you need to parse the error body, try with this code:

if (response.isSuccessful()) { 
// Do your success stuff...
 } else
JSONObject jObjError = new JSONObject(response.errorBody().string());
 Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
 } catch (Exception e) {
 Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();

Of course that you can use another parser like Gson .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download