Why does GSON use ONLY fields(private,public,protected)? Is there a way to tell GSON to use only getters and setters?
Java Gson fromJson The fromJson method deserializes the specified JSON into an object of the specified class. The example uses fromJson method to read JSON into a Java object. Notice that getters and setters are not necessary.
Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
Gson serializer will ignore every field declared as transient: String jsonString = new Gson().
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With