2017-01-25 1 views
1

Я получаю null в корпусе Response в модификации 2. тогда как в теле у меня есть действительные данные.Получение нулевого ответа даже в случае успешного запроса в Retrofit 2

//using retrofit 
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 
    logging.setLevel(HttpLoggingInterceptor.Level.BODY); 
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 
    httpClient.addInterceptor(logging); 

    Retrofit adapter = new Retrofit.Builder() 
         .baseUrl(Config.CUSTOMER_URL) 
         .addConverterFactory(GsonConverterFactory.create()) 
         .client(httpClient.build()) 
         .build(); 
    RegisterCustomer api = adapter.create(RegisterCustomer.class); 
    Call<Model> call = api.registerCustomer(custName.getText().toString() , phoneNumber.getText().toString(), address.getText().toString(), "abc"); 
    call.enqueue(new Callback<Model>() { 
     @Override 
     public void onResponse(Call<Model> call, retrofit2.Response<Model> response) { 
      if(response.isSuccessful()) 
      { 
       Log.d("CallBack",response.body().getCustId()+"###"+response.body().getCustUri()+response.code()); 
      } 

     } 

     @Override 
     public void onFailure(Call<Model> call, Throwable t) { 
      Log.d("CallBack","error saving customer"+t.getMessage()); 

     } 
    }); 

Мой интерфейс.

public interface RegisterCustomer 
{ 
    @FormUrlEncoded 
    @POST("customer") 
    Call<Model> registerCustomer(
      @Field("cust_name") String cust_name, 
      @Field("phone") String phone, 
      @Field("address") String address, 
      @Field("apikey") String apikey 
    //  Callback<Response> callback 
    ); 
} 

Мой LogCat ниже:

01-25 12:52:26.139 12163-12525/com.lab.yourhomebasket D/OkHttp: --> POST http://192.168.0.101/grocery_api/customer http/1.1 
01-25 12:52:26.139 12163-12525/com.lab.yourhomebasket D/OkHttp: Content-Type: application/x-www-form-urlencoded 
01-25 12:52:26.142 12163-12525/com.lab.yourhomebasket D/OkHttp: Content-Length: 57 
01-25 12:52:26.142 12163-12525/com.lab.yourhomebasket D/OkHttp: cust_name=deep&phone=6656455465&address=bhdjih&apikey=abc 
01-25 12:52:26.142 12163-12525/com.lab.yourhomebasket D/OkHttp: --> END POST (57-byte body) 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: <-- 201 Created http://192.168.0.101/grocery_api/customer (386ms) 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Date: Wed, 25 Jan 2017 07:22:29 GMT 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Server: Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.4 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: X-Powered-By: PHP/7.0.4 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Content-Length: 42 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Keep-Alive: timeout=5, max=100 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Connection: Keep-Alive 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: Content-Type: application/json;charset=utf-8 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: {"cust_id":18,"cust_uri":"\/customer\/18"} 
01-25 12:52:26.529 12163-12525/com.lab.yourhomebasket D/OkHttp: <-- END HTTP (42-byte body) 
01-25 12:52:26.533 12163-12163/com.lab.yourhomebasket D/CallBack: null###null201 

Мой действительный ответ { "cust_id": 18, "cust_uri": "/ клиент/18"} Я получаю нулевой ### null201 также данные успешно сохраняются на сервере.

Model.java

  import com.fasterxml.jackson.annotation.JsonProperty; 
     import java.util.HashMap; 
     import java.util.Map; 
     import com.fasterxml.jackson.annotation.JsonAnyGetter; 
     import com.fasterxml.jackson.annotation.JsonAnySetter; 
     import com.fasterxml.jackson.annotation.JsonIgnore; 
     import com.fasterxml.jackson.annotation.JsonInclude; 
     import com.fasterxml.jackson.annotation.JsonProperty; 
     import com.fasterxml.jackson.annotation.JsonPropertyOrder; 

@JsonInclude(JsonInclude.Include.NON_NULL) 
@JsonPropertyOrder({ 
     "cust_id", 
     "cust_uri" 
}) 
public class Model { 

    @JsonProperty("cust_id") 
    private Integer custId; 
    @JsonProperty("cust_uri") 
    private String custUri; 
    @JsonIgnore 
    private Map<String, Object> additionalProperties = new HashMap<String, Object>(); 

    @JsonProperty("cust_id") 
    public Integer getCustId() { 
     return custId; 
    } 

    @JsonProperty("cust_id") 
    public void setCustId(Integer custId) { 
     this.custId = custId; 
    } 

    @JsonProperty("cust_uri") 
    public String getCustUri() { 
     return custUri; 
    } 

    @JsonProperty("cust_uri") 
    public void setCustUri(String custUri) { 
     this.custUri = custUri; 
    } 

    @JsonAnyGetter 
    public Map<String, Object> getAdditionalProperties() { 
     return this.additionalProperties; 
    } 

    @JsonAnySetter 
    public void setAdditionalProperty(String name, Object value) { 
     this.additionalProperties.put(name, value); 
    } 

} 

Благодаря Дипак

+0

добавить 'Model.java' также. – Saurabh

+0

Вы добавили 'GsonConvertorFactory' вашему ретрофитному клиенту, но вы использовали Jackson для разбора json. Вам либо нужно изменить модель, чтобы она соответствовала Gson, как указано в ответе ниже, либо использовать преобразователь jackson для модификации – akash93

ответ

1

Можете ли вы проверить ваш Model.java должен быть, как показано ниже.

public class Model { 

@SerializedName("cust_id") 
@Expose 
private Integer custId; 
@SerializedName("cust_uri") 
@Expose 
private String custUri; 

public Integer getCustId() { 
return custId; 
} 

public void setCustId(Integer custId) { 
this.custId = custId; 
} 

public String getCustUri() { 
return custUri; 
} 

public void setCustUri(String custUri) { 
this.custUri = custUri; 
} 

} 
+0

Спасибо Mehul, это решает проблему. –

+0

Приветственный человек .... nJoy ... !! –

+1

Вы должны указать причину, по которой эта модель работает так, чтобы люди не просто копировали пасту, но понимали, почему работает этот код – akash93

Смежные вопросы