2

When I have an entity like this

class Foo
{
   private String Bar = "someBarValue";
}

and the following statement

String json = new Gson().toJson(new Foo());

results in { "bar" : "someBarValue"}

I have lots of classes that follow the standard java bean convention

class FooBean
{
    String getBar() { return "someBarValue"; }
}

and the following statement

String json = new Gson().toJson(new FooBean());

results in {}

How can I serialize (and eventually deserialize, if I have setters) FooBean from the above example using Gson without having to rely on the private member variables of a class?

FelipeAls
  • 21,711
  • 8
  • 54
  • 74
Professor Chaos
  • 8,850
  • 8
  • 38
  • 54

1 Answers1

4

This is not possible as of today. Have a look at Gson Design Document:

Using fields vs getters to indicate Json elements

Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties.

However, there 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.

Another thing that you might consider is the concept of serialization/deserialization: why would one serialize/deserialize an object? In general, to have a copy of it after persistence, communication (i.e., mainly I/O). It makes sense not to rely on getters and setters to do so. They might change the contents of the objects, and so serialization/deserialization would not be achieving what they were built for.

Community
  • 1
  • 1
Viccari
  • 9,029
  • 4
  • 43
  • 77
  • Right now I realized this topic is covered here: http://stackoverflow.com/questions/6203487/why-does-gson-use-fields-and-not-getters-setters So, giving the credit to someone who answered first. – Viccari Mar 02 '13 at 21:48