开发者

Why does GSON use fields and not getters/setters?

开发者 https://www.devze.com 2023-03-09 15:34 出处:网络
Why does G开发者_C百科SON use ONLY fields(private,public,protected)? Is there a way to tell GSON to use only getters and setters?Generally speaking when you serialize/deserialize an object, you are do

Why does G开发者_C百科SON use ONLY fields(private,public,protected)? Is there a way to tell GSON to use only getters and setters?


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.


It is possible to to patch Gson to use getters.


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...)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号