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中文網其他相關文章!