Java Google Json (Gson) New in Gson 2.3

What’s new in Gson 2.3

In this article we look at the additions in Google Json 2.3. There are three main changes :

we now present examples for all three

@TypeAdapter Annotation

TypeAdapters are used to specify rules to convert a java class to json and other way round. Look at this tutorial to understand how type adapters work. We look at the same example but use an annotation instead. The example deals with parsing the free music api gson string. We hit the free music api and get the top 5 albums along with the datasets of each album. Look at this link to see the json. The Album info is stored in the Album class and the datasets in the Dataset class. Here are the classes

Notice how the Dataset class is annotated with the @JsonAdapter. Lets look at the adapter

As explained in the comments we use a TypeAdapter since we dont want to populate the Dataset object in the default way, but use special rules. Here’s the main method

Next, lets look at the JsonPath support added in gson 2.3

JsonPath Support

To understand JsonPath look at this link. JsonPath is to Json what XPath is to XML. Gson has a new method in JsonReader class that gives the path of the element where the JsonReader cursor is. To demonstrate JsonPath we use the same example as above, i.e. the music archive. We print the json path for each string element.

The output of the program is show below. It gives an idea of how the jsonpath looks like.

The last part is the new methods in jsonarray

New Methods in JsonArray

We look at four new methods added in JsonArray : contains(JsonElement), remove(JsonElement), remove(int index), set(int index, JsonElement element). The contains method checks whether the array contains the particular element, the remove method has two variants: one that takes in an index and other that takes in the actual element to be removed. The last method is the set method that sets a new element at a particular index. The example below demonstrates all four methods.

Leave a Reply

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