JSON Manipulation Using GSON
Let's explore a JSON manipulation using GSON.
Join the DZone community and get the full member experience.
Join For FreeThere 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:
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!
Opinions expressed by DZone contributors are their own.
Comments