Ignore attribute in POST using Retrofit

3

I would like to know how to ignore an attribute of a model in a POST request with Retrofit. In GET requests I want to bring all attributes, but in requests POST I need to send the object without id for example.

Sample Model :

public class Model {

  int id;               // ignorar este atributo
  String atributo1;
  String atributo2;
  String atributo3;     // ignorar este atributo

  // ... getters and setters

}

Service Example:

public interface ModelService {

  @POST("resources")
  Call<Model> create(@Body Model model) // enviar objeto sem id e atributo3

}

Sample execution:

Retrofit retrofit = new Retrofit.Builder()
         .baseUrl(BASE_URL)
         .addConverterFactory(GsonConverterFactory.create())
         .build();

ModelService modelService = retrofit.create(ModelService.class);
Call<Model> call = modelService.create(collection);

call.enqueue(new Callback<Model>() {

  // ... onResponse / onFailure

});

Is there a possibility or need to be implemented differently? Or maybe I should treat this in backend ?

    
asked by anonymous 01.08.2017 / 22:11

1 answer

4

If you want id not to appear in serialized JSON, one way is to use transient . See:

private transient int id;

See more details about% in and also in that question about what is the purpose of transient and Transient in Java .

Or, if you prefer, you can use Volatile ". See:

@Expose
private int id;

So, just use the @Expose method. See:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    
01.08.2017 / 22:33