我有以下带有一个字段 transient 的 Pojo 类:
public class User implements Serializable {
public static final long serialVersionUID = 1L;
public String name;
transient public UserSession[] bookings;
}
我希望使用 Gson 库对 transient 文件进行序列化和反序列化,但不希望在文件上对文件进行序列化。 我怎样才能实现它?
最佳答案
如前所述in the documentation :
By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as "static" then by default it will be excluded. If you want to include some transient fields then you can do the following:
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create();
这将从 Gson 序列化中排除 static
字段,但不包括 transient
和 volatile
字段。
关于java - Gson反序列化和序列化 transient 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669876/