Home > Java > javaTutorial > body text

How to exclude a field from JSON using @Expose annotation in Java?

PHPz
Release: 2023-09-16 21:49:02
forward
643 people have browsed it

How to exclude a field from JSON using @Expose annotation in Java?

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.

Syntax

public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Copy after login

Example

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;
   }
}
Copy after login

Output

{
 "name": "Raja",
 "age": 28,
 "salary": 40000.0
}
{
 "name": "Raja",
 "age": 28
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template