Gaurav Singla
Gaurav Singla

Reputation: 1451

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?

Upvotes: 7

Views: 6309

Answers (1)

dotvav
dotvav

Reputation: 2848

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.

Upvotes: 22

Related Questions