Java Gson – Building json from java (Data-Binding)

Converting a java object to json

Gson is quite powerful when you simply want to build json from a java object. It does not require anything fancy, just pass the java object and you are done. However, it does allow customizations. You can control what goes inside the json from the java object and you can also control the names of the json properties. But more about that later. The example below simply takes a java object and spits out a json string.

Albums class

Dataset class

Building a json from Primitive types and String

If you dont want to build json from a java object but want to build it from scratch then look at the example below. In this example we also show some of the features that can be configured using the GsonBuilder class. Chiefly, the class shows the following:

  1. Serializing Null– By Default, nulls are not serialized, however that can be changed by setting serializeNulls() in the GsonBuilder.
  2. FieldNamingPolicy-Field names can be specified to follow a particular strategy. i.e. UPPER_CAMEL_CASE, UPPER_CAMEL_CASE_WITH_SPACES, LOWER_CASE_WITH_UNDERSCORES, LOWER_CASE_WITH_DASHES.
  3. Pretty Printing – For better visual appearance the json can be printed with proper indentation. This should not be used when sending data.

One thought on “Java Gson – Building json from java (Data-Binding)

  • August 2, 2017 at 12:20 pm
    Permalink

    Excelenteee!!!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *