如何排除Gson序列化中的Java字段?
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 class class 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 }
广告