Why does GSON use fields and not getters/setters?

Why does GSON use ONLY fields(private,public,protected)? Is there a way to tell GSON to use only getters and setters?


Solution 1:

Generally speaking when you serialize/deserialize an object, you are doing so to end up with an exact copy of the state of the object; As such, you generally want to circumvent the encapsulation normally desired in an OO design. If you do not circumvent the encapsulation, it may not be possible to end up with an object that has the exact same state after deserialization as it had prior to serialization. Additionally, consider the case where you do not want to provide a setter for a particular property. How should serialization/deserialization act if you are working through the getters and setters?

Solution 2:

Is there a way to tell GSON to use only getters and setters?

Not yet.

From the design doc:

[T]here are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based.

Solution 3:

It is possible to to patch Gson to use getters.