Gson库提供了一种简单的方法,可以使用transient修饰符来排除序列化中的字段。如果我们将Java类中的字段设置为transient,则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.<strong>toJson</strong>(p); System.out.println(jsonStr); } } //Person class<strong> </strong>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 }
以上是在Java中如何在Gson序列化过程中排除一个字段?的详细内容。更多信息请关注PHP中文网其他相关文章!