Sunday, August 22, 2021

Post#140-API#9 Parsing Json String using GSON library

 👇

To use GSON library you have to add maven dependency in your project.

GSON as a Maven dependency looks like this:

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

 Let's take the below JSON as an example:

{

    "page": 2,

    "per_page": 6,

    "total": 12,

    "total_pages": 2,

    "data": [

        {

            "id": 7,

            "email": "michael.lawson@reqres.in",

            "first_name": "Michael",

            "last_name": "Lawson",

            "avatar": "https://reqres.in/img/faces/7-image.jpg"

        },

        {

            "id": 8,

            "email": "lindsay.ferguson@reqres.in",

            "first_name": "Lindsay",

            "last_name": "Ferguson",

            "avatar": "https://reqres.in/img/faces/8-image.jpg"

        }

    ],

    "support": {

        "url": "https://reqres.in/#support-heading",

        "text": "To keep ReqRes free, contributions towards server costs are appreciated!"

    }

}

Java Program-1: Read per_page element value from the above Json String.

import java.io.IOException;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

public class Program1 {

public static void main(String[] args) throws IOException {

String details = "{\"page\":2,\"per_page\":6,\"total\":12,\"total_pages\":2,\"data\":[{\"id\":7,\"email\":\"michael.lawson@reqres.in\",\"first_name\":\"Michael\",\"last_name\":\"Lawson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/7-image.jpg\"},{\"id\":8,\"email\":\"lindsay.ferguson@reqres.in\",\"first_name\":\"Lindsay\",\"last_name\":\"Ferguson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/8-image.jpg\"}],\"support\":{\"url\":\"https:\\/\\/reqres.in\\/#support-heading\",\"text\":\"To keep ReqRes free, contributions towards server costs are appreciated!\"}}";

JsonObject jsonObject = new JsonParser().parse(details).getAsJsonObject();

String per_page = jsonObject.get("per_page").getAsString();

System.out.println(per_page);

}}

O/P - 6

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

You might be thinking what is JsonObject 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 super class 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.

Java Program-2: Read url element value under support object from the above Json String.

import java.io.IOException;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

 public class Program2 {

public static void main(String[] args) throws IOException {

String details = "{\"page\":2,\"per_page\":6,\"total\":12,\"total_pages\":2,\"data\":[{\"id\":7,\"email\":\"michael.lawson@reqres.in\",\"first_name\":\"Michael\",\"last_name\":\"Lawson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/7-image.jpg\"},{\"id\":8,\"email\":\"lindsay.ferguson@reqres.in\",\"first_name\":\"Lindsay\",\"last_name\":\"Ferguson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/8-image.jpg\"}],\"support\":{\"url\":\"https:\\/\\/reqres.in\\/#support-heading\",\"text\":\"To keep ReqRes free, contributions towards server costs are appreciated!\"}}";

JsonObject jsonObject = new JsonParser().parse(details).getAsJsonObject();

String url = jsonObject.getAsJsonObject("support").get("url").getAsString();

System.out.println(url);

}}

O/P - https://reqres.in/#support-heading

Code explanation : Here url element is resides inside support Object. Hence we used getAsJsonObject() method to get the support object. Then we use get("url") method to get the url element value.

Java Program-3: Read 1st email element value under data array from the above Json String.

import java.io.IOException;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

 public class Program3 {

 public static void main(String[] args) throws IOException {

String details = "{\"page\":2,\"per_page\":6,\"total\":12,\"total_pages\":2,\"data\":[{\"id\":7,\"email\":\"michael.lawson@reqres.in\",\"first_name\":\"Michael\",\"last_name\":\"Lawson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/7-image.jpg\"},{\"id\":8,\"email\":\"lindsay.ferguson@reqres.in\",\"first_name\":\"Lindsay\",\"last_name\":\"Ferguson\",\"avatar\":\"https:\\/\\/reqres.in\\/img\\/faces\\/8-image.jpg\"}],\"support\":{\"url\":\"https:\\/\\/reqres.in\\/#support-heading\",\"text\":\"To keep ReqRes free, contributions towards server costs are appreciated!\"}}";

JsonObject jsonObject = new JsonParser().parse(details).getAsJsonObject();

String email = jsonObject.getAsJsonArray("data").get(0).getAsJsonObject().get("email").getAsString();

System.out.println(email);

}}

O/P - michael.lawson@reqres.in

Code explanation – Here data is a array node. Hence used getAsJsonArray("data"). Under this node there are multiple objects are present. But our objective is to get the 1st Object. Hence used get(0).getAsJsonObject(). Now you have the JsonObject and you can get the email element value by using get("email").getAsString().

Program-3 – Sometime you may get the complete Json String as Array. In this case you can parse the Json as JsonArray as below example.

String str = "[\"Selenium\", \"Java\", \"SoapUI\"]";

JsonArray array = new JsonParser().parse(str).getAsJsonArray();

Program-4 - We can check if any jsonAttribute is null by calling the isJsonNull() method of JsonElement as below.

if(jsonObject.get("Manish").isJsonNull()){  

            System.out.println("Manish is null");

          }


Hope this helps 🙏





No comments:

Post a Comment