Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GSON use fields and not getters/setters?

Tags:

java

gson

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

like image 537
Zemzela Avatar asked Jun 01 '11 15:06

Zemzela


People also ask

Does Gson use 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.

Why are getters and setters bad?

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.

Does Gson ignore unknown fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

Does Gson ignore transient fields?

Gson serializer will ignore every field declared as transient: String jsonString = new Gson().


2 Answers

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?

like image 132
Chris Shaffer Avatar answered Oct 02 '22 03:10

Chris Shaffer


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.

like image 23
Programmer Bruce Avatar answered Oct 02 '22 03:10

Programmer Bruce