How to ignore some variables in models using for retrofit

前端 未结 3 1980
小鲜肉
小鲜肉 2021-01-12 01:38

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 th

相关标签:
3条回答
  • 2021-01-12 01:55

    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.

    0 讨论(0)
  • 2021-01-12 01:56

    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();
    
    0 讨论(0)
  • 2021-01-12 02:06

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

    JAVA:

    transient String name;
    

    KOTLIN:

    @Transient
    var name: String
    
    0 讨论(0)
提交回复
热议问题