Why does GSON use fields and not getters/setters?

JavaGson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

> 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 - Java

It is possible to to patch Gson to use getters.

Solution 4 - Java

The vague outline of how this works in our app is that we have a lot of TypeAdapter implementations - some for specific value-like objects and some for bean-style objects where we know that JavaBeans logic will work. We then jam all of these onto a GsonBuilder before creating the Gson object.

Unfortunately, GSON is really crap at handling types like Object[]. We mostly saw this when we were trying to make a JSON object to represent method parameters. The workaround for that was to make custom TypeAdapter instances which reflect the methods. (This does mean that you end up using one Gson instance per method you intend to call...)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZemzelaView Question on Stackoverflow
Solution 1 - JavaChris ShafferView Answer on Stackoverflow
Solution 2 - JavaProgrammer BruceView Answer on Stackoverflow
Solution 3 - JavaJimmyView Answer on Stackoverflow
Solution 4 - JavaHakanaiView Answer on Stackoverflow