Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson deserialize and serialize transient field

I have following Pojo Class with one field transient :

public class User implements Serializable {

    public static final long serialVersionUID = 1L;
    public String name;
    transient public UserSession[] bookings;
}

I want the transient filed be serialized and deserialized with Gson library but don't want the filed to be serialized on File. How can i achieve it?

like image 696
Gaurav Singla Avatar asked Jul 28 '15 07:07

Gaurav Singla


1 Answers

As stated 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();

Which will exclude static fields from Gson serialization, but not transient and volatile ones.

like image 164
dotvav Avatar answered Oct 04 '22 05:10

dotvav