By default when an object is serialized to json format, all the properties in the object are serialized.
We can prevent this default behavior, by annotating the property with @JsonbTransient annotation.
Below is the example. The class to be serialized is Employee
Employee
1 import javax.json.bind.annotation.JsonbTransient;
2
3 public class Employee {
4 private int id;
5 private String name;
6 private int ssn;
7
8 public int getId() {
9 return id;
10 }
11
12 public void setId(int id) {
13 this.id = id;
14 }
15
16 public String getName() {
17 return name;
18 }
19
20 public void setName(String name) {
21 this.name = name;
22 }
23
24 @JsonbTransient
25 public int getSsn() {
26 return ssn;
27 }
28
29 public void setSsn(int ssn) {
30 this.ssn = ssn;
31 }
32 }
When the object of an employee class is serialized. I want all properties except ssn to serialized. To do this I mark getSsn method with the annotation. Refer to line 24 in the above code.
The main code is as shown below
Main Code
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class JsonbDemo6 {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(1);
emp.setName("name1");
emp.setSsn(9);
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(emp);
System.out.println(result);
}
}
Output
{“id”:1,”name”:”name1″}