12

I am using Retrofit to send and receive requests to my server.

I Have a model like below and I have to send it to my server but some variables in this model have not to send to the server.

public class SelectedListModel implements Serializable {

  @SerializedName("p_id")
  @Expose
  private Long pId;

  @SerializedName("p_qty")
  @Expose
  private Double pQty;

  @Expose(serialize = false , deserialize = false)
  private String pName; //Have not to send to server

  @Expose(serialize = false , deserialize = false)
  private String pPrice; //Have not to send to server

  @Expose(serialize = false , deserialize = false)
  private String pImageUrl; //Have not to send to server
}

and because of that, I am getting 400 in my responses from the server. I used of @Expose(serialize = false, deserialize = false) in order to Ignore variables that have not to send to the server. But it doesn't work. Is there any way to do this or I have to create another model just for my server?

Community
  • 1
  • 1
Ehsan
  • 2,676
  • 6
  • 29
  • 56

3 Answers3

15

Use transient keywork for that

public class SelectedListModel implements Serializable {

  @SerializedName("p_id")
  @Expose
  private Long pId;

  @SerializedName("p_qty")
  @Expose
  private Double pQty;

  //@Expose(serialize = false , deserialize = false)
  private transient String pName; //Have not to send to server

  //@Expose(serialize = false , deserialize = false)
  private transient String pPrice; //Have not to send to server

  //@Expose(serialize = false , deserialize = false)
  private transient String pImageUrl; //Have not to send to server
}

and no need to use @Expose(serialize = false , deserialize = false), into those fields which needed to be excluded.


Read Why does Java have transient fields? and Why use the `transient` keyword in java? for more details.

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
7

You can use transient keyword to ignore fields when requesting api calls

JAVA:

transient String name;

KOTLIN:

@Transient
var name: String
Amir Raza
  • 2,320
  • 1
  • 23
  • 32
0

change your Retrofit adapter code like this (I hope you're using retrofit2)

Gson gson = new GsonBuilder()
     .excludeFieldsWithoutExposeAnnotation()
     .create();

Retrofit retrofit = new Retrofit.Builder()  
     .baseUrl(BASE_URL)
     .addConverterFactory(GsonConverterFactory.create(gson))
     .build();
VinayagaSundar
  • 1,673
  • 17
  • 18