Parse json string and java object into Gson tree model

GSON Tree Model API provides JsonParser help you parse Json string to tree model of JsonElement. Beside, JsonElement provides method isJsonXXX() and getAsYYY() to check type of Json element and get value of element on that tree node.
On the writing, Gson Tree Model API provides method toJsonTree help you converts a java object into a tree JsonElement also. Using this JsonElement you could manipulate the Tree Model at runtime, for example add/update/remove fields/property.

Other interesting posts you may like

Now you should practice with gson completed sample below.

GSON Tree Model API library dependency should be added in pom.xml

Read JSON data from input file, for example input.json

This program reads json data from file then display output

Run it and you should get the output

You also add/update/remove on tree model and convert it into Json string.

The bean Fruit is used to setup data for tree model json

Here is a ouput

Give you other bonus on how to Convert Java collections into JSON and JSON to collections

Leave a Comment


Please share it if you found this useful
Hide Buttons