如何在 Java 序列化期间排除 Gson 中的字段?
javajsonobject oriented programmingprogramming
Gson 库提供了一种使用 transient 修饰符从序列化中排除字段的简单方法。如果我们将 Java 类中的字段设为瞬时,则 Gson 可以 忽略序列化 和反序列化。
示例
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 classclass Person { private String firstName; private transient String lastName; private int age; private transient double salary; public Person(String firstName, String lastName, int age, double salary) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.salary = salary; } }
输出
{ "firstName": "Raja", "age": 28 }