Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JSON Manipulation Using GSON

DZone 's Guide to

JSON Manipulation Using GSON

Let's explore a JSON manipulation using GSON.

· Integration Zone ·
Free Resource

There are various libraries for parsing and manipulating JSON, like objectMapper, net.sf, and GSON. We will be discussing the JSON library in-depth.

You can add the GSON dependency through Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>

Let's take the below JSON as an example:

{
"name": "John",
"address": {
"city": "London",
"plot": 12
},
"age": 23,
"registered": true,
"isEligible": false,
"hobbies": ["music", "tech news", "blog"],
"birthMark": null
}

We parse the JSON string by creating the object of JsonParser and calling its parse method.

String details = "{\"name\":\"John\",\"address\":{\"city\":\"London\",\"plot\":12},\"age\":23,\"registered\":true,\"isEligible\":false,\"hobbies\":[\"music\",\"tech news\",\"blog\"],\"birthMark\":null}";
JsonObject jsonObject = new JsonParser().parse(details).getAsJsonObject();

You wonder what is JsonObject of type. Whenever we parse a JSON string, the object that we get is of type JsonElement. JsonElement in GSON is similar to the object class in Java, which is the superclass of all JSON. It then further extends to the below types:

Image title

A valid JSON that we are going to parse can be a JsonObject or a JsonArray, hence whenever we parse the JSON, we get the object of JsonElement and then we have to use either the getAsJsonObject() or getAsJsonArray() method to get the object of the desired type. We have used getAsJsonObect() method in our case, based on our example.

Below is the example of a valid JSON array and how we can parse it.

String str = "[\"Ford\", \"BMW\", \"Fiat\"]";
JsonArray array = new JsonParser().parse(str).getAsJsonArray();

We can check if any jsonAttribute is null by calling the isJsonNull() method of JsonElement.

if(jsonObject.get("birthMark").isJsonNull()){   
  System.out.println("birthMark is null");
}

Thanks for reading!

Topics:
java ,gson ,json ,integration ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}