Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a JSON element in Android Retrofit

Tags:

I am developing an Android App which is sending a JSON using Android Retrofit (it converts a POJO class in a JSON). It is working fine, but I need to ignore in the sending of JSON one element from the POJO class.

Does anyone know any Android Retrofit annotation?

Example

POJO Class:

public class sendingPojo {    long id;    String text1;    String text2;//--> I want to ignore that in the JSON     getId(){return id;}    setId(long id){      this.id = id;    }     getText1(){return text1;}    setText1(String text1){      this.text1 = text1;    }     getText2(){return text2;}    setText2(String text2){      this.text2 = text2;    }   } 

Interface Sender ApiClass

 public interface SvcApi {   @POST(SENDINGPOJO_SVC_PATH)  public sendingPojo addsendingPojo(@Body sendingPojo sp);  } 

Any idea how to ignore text2?

like image 954
Alberto Crespo Avatar asked Aug 10 '15 14:08

Alberto Crespo


People also ask

What is @body in retrofit?

Retrofit offers the ability to pass objects within the request body. Objects can be specified for use as HTTP request body by using the @Body annotation. The functionality of Retrofit's @Body annotation hasn't changed in version 2.

What is retrofit JSON?

Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.


2 Answers

I found an alternative solution if you don't want to use new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() .

Just including transient in the variable I need to ignore.

So, the POJO class finally:

public class sendingPojo {     long id;     String text1;     transient String text2;//--> I want to ignore that in the JSON      getId() {         return id;     }      setId(long id) {         this.id = id;     }      getText1() {         return text1;     }      setText1(String text1) {         this.text1 = text1;     }      getText2() {         return text2;     }      setText2(String text2) {         this.text2 = text2;     } } 

I hope it helps

like image 70
Alberto Crespo Avatar answered Sep 18 '22 13:09

Alberto Crespo


Mark the desired fields with the @Expose annotation, such as:

@Expose private String id; 

Leave out any fields that you do not want to serialize. Then just create your Gson object this way:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 
like image 41
nikhil.thakkar Avatar answered Sep 20 '22 13:09

nikhil.thakkar