Why static fields not serialized using google.gson.GsonBuilder JSON parser? Why static fields not serialized using google.gson.GsonBuilder JSON parser? json json

Why static fields not serialized using google.gson.GsonBuilder JSON parser?


but if someone wants to include static, change the builder to just ignore transient, since you will override the the default of both transient and static to just transient.

GsonBuilder gsonBuilder  = new GsonBuilder();// Allowing the serialization of static fields    gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);    // Creates a Gson instance based on the current configuration    Gson gson = gsonBuilder.create();    String json = gson.toJson(objectToSerialize);    System.out.println(json);


Java Serialization only serialize object's non-static and non-transient fields because,

The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

Reference

In case of static field state not only belongs to any specific object it will belongs to all class.

So the static field would be comes under state of any specific object.