The Gson @Expose คำอธิบายประกอบ สามารถใช้เพื่อทำเครื่องหมายฟิลด์ที่จะเปิดเผยหรือไม่ (รวมหรือไม่) สำหรับซีเรียลไลซ์หรือดีซีเรียลไลซ์ คำอธิบายประกอบ @Expose สามารถรับพารามิเตอร์ได้ 2 ตัว และแต่ละพารามิเตอร์เป็นบูลีนซึ่งรับค่าใดค่าหนึ่ง จริง หรือ เท็จ . เพื่อให้ GSON ตอบสนองต่อคำอธิบายประกอบ @Expose เราต้องสร้างอินสแตนซ์ Gson โดยใช้ GsonBuilder และจำเป็นต้องเรียก excludeFieldsWithoutExposeAnnotation() เมธอดจะกำหนดค่า Gson เพื่อแยกฟิลด์ทั้งหมดออกจากการพิจารณาสำหรับการทำให้เป็นอนุกรมหรือการดีซีเรียลไลซ์เซชั่นที่ไม่มีคำอธิบายประกอบการเปิดเผย
ไวยากรณ์
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)
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
}