Gson @Expose annotation can be used to mark whether a field is exposed (contained or not) for serialization or deserialization. @Expose Notes Can take two parameters, each parameter is a Boolean value, can take the value true or false. In order for GSON to react to the @Expose annotation, we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, which configures Gson to exclude all fields without Expose The annotated fields are serialized or deserialized.
public GsonBuilder excludeFieldsWithoutExposeAnnotation()
import com.google.gson.*; import com.google.gson.annotations.*; public class JsonExcludeAnnotationTest { public static void main(String args[]) { Employee emp = new Employee("Raja", 28, 40000.00); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonStr = gson.toJson(emp); System.out.println(jsonStr); gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); jsonStr = gson.toJson(emp); System.out.println(jsonStr); } } // Employee class class Employee { @Expose(serialize = true, deserialize = true) public String name; @Expose(serialize = true, deserialize = true) public int age; @Expose(serialize = false, deserialize = false)<strong> </strong> public double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } }
{ "name": "Raja", "age": 28, "salary": 40000.0 } { "name": "Raja", "age": 28 }
The above is the detailed content of How to exclude a field from JSON using @Expose annotation in Java?. For more information, please follow other related articles on the PHP Chinese website!