Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี Exclude Field ใน Gson ระหว่าง Serialization ด้วย Transient ใน Java

ไลบรารี Gson ให้วิธีง่ายๆ ในการ Exclude Field จาก Serialization โดยใช้ Modifier transient หาก Field ใดใน Java Class ถูกประกาศเป็น transient Gson จะ Ignore Field นั้นทั้ง Serialization และ Deserialization

ตัวอย่าง: ใช้ transient Exclude Field

import com.google.gson.*;

public class GsonTransientFieldTest {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Person p = new Person("Raja", "Ramesh", 28, 35000.00);
        String jsonStr = gson.toJson(p);
        System.out.println(jsonStr);
    }
}

// Person class
class Person {
    private String firstName;
    private transient String lastName;   // จะถูก exclude
    private int age;
    private transient double salary;     // จะถูก exclude
    
    public Person(String firstName, String lastName, int age, double salary) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.salary = salary;
    }
}

ผลลัพธ์

{
  "firstName": "Raja",
  "age": 28
}

สรุป: Field ที่มี transient จะไม่ปรากฏใน JSON Output และจะไม่ถูก Deserialize กลับเข้ามา วิธีนี้ง่ายที่สุดสำหรับ Field ที่ไม่ต้องการ Serialize เช่น Password, Temporary Data, Calculated Fields เป็นต้น