How to exclude json fields in Gson APIs?
This page shows how to exclude certain json fields when using Gson APIs. It is a 2 step process. Firstly annotate your POJO
member variables with @Expose annotation, remember that don't annotate the fields which you don't want to be part of json output. As a second
step, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). Now the
json output will include all members which has annotated with @Expose annotation.
Note: Refer How to convert java object to json string using Gson APIs? page for dependent libraries.
Here is the sample POJO which has members annotated with @Expose annotation. Notice that "salary" field is not annotated
with @Expose annotation which is not part of the output.
package com.java2novice.json.gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Employee {
@Expose
@SerializedName("emp_id")
private int empId;
@Expose
@SerializedName("emp_name")
private String name;
@Expose
private String designation;
@Expose
private String department;
private int salary;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
|
Note that the Gson obect creation is using excludeFieldsWithoutExposeAnnotation() method call.
package com.java2novice.json.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class ObjectToJsonEx {
public static void main(String a[]){
Employee emp = new Employee();
emp.setEmpId(1016);
emp.setName("Nataraj G");
emp.setSalary(20000);
emp.setDesignation("Manager");
emp.setDepartment("Accounts");
Gson gsonObj = new GsonBuilder()
.setPrettyPrinting()
.excludeFieldsWithoutExposeAnnotation()
.create();
// converts object to json string
String jsonStr = gsonObj.toJson(emp);
System.out.println(jsonStr);
}
}
|
|