Why does GSON use fields and not getters/setters?

Zemzela picture Zemzela · Jun 1, 2011 · Viewed 46.6k times · Source

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

Answer

Chris Shaffer picture Chris Shaffer · Jun 1, 2011

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?