Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Sunday, July 24, 2022

How to parse JSON string to Object and vice versa in Groovy Grails application

In this tutorial, we will learn how to parse or convert the object to JSON string and JSON string to object.

Convert Object to JSON String:

Let's look into the example, here we will parse the Map to JSON string.

Map mapToConvert = [username : "Test", phonenumber : "+10656564"]
List listToConvert = ["Test", "+10656564"]

Now, let's convert to JSON string using JSON class

import grails.converters.JSON
        Map mapToConvert = [username : "Test", phonenumber : "+10656564"]
        List listToConvert = ["Test", "+10656564"]
        String jsonStringFromMap =  (mapToConvert as JSON).toString()
        String jsonStringFromList =  (listToConvert as JSON).toString()
        

You can use any other object data type to convert as above

Convert JSON String to Object:

For converting JSON string to object we are using JsonSlurper as below:

import grails.converters.JSON
import groovy.json.JsonSlurper
		Map mapToConvert = [username : "Test", phonenumber : "+10656564"]
        List listToConvert = ["Test", "+10656564"]
        String jsonStringFromMap =  (mapToConvert as JSON).toString()
        String jsonStringFromList =  (listToConvert as JSON).toString()
        Map convertedMap = parseTo(jsonStringFromMap)
        List convertedList = parseTo(jsonStringFromList)
        
        private static def parseTo(String jsonString) {
        return new JsonSlurper().parseText(jsonString)
    }
        
Share:

Saturday, June 13, 2020

How to convert the JSON file to Map and List in Java using Gson.

In this post, we are going to convert the JSON file to Map or List. Here, we are using the Gson library which provides a clean way to do so. You can download the Gson jar file from here.


Now, load the jar file from your IDE.

For IntelliJ Idea:

Go to: File >> Project Structure(Ctr + Alt + Shift + s) >> Libraries and click the + icon on the top left corner and select library file that we downloaded. Apply and save. If you are using in an existing project like Gradle or Maven: 

For Gradle:

Inside build.gradle file under dependencies,
compile 'com.google.code.gson:gson:2.8.6'



For Maven:

Inside pom.xml
<dependency>
  <groupid>com.google.code.gson</groupid>
  <artifactid>gson</artifactid>
  <version>2.8.6</version>
</dependency>

Create a Class that converts a JSON file to Map or List.
package jsonToMap;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;


public class JsonConverter {

    public static void main(String[] args) {
        String baseDir = System.getProperty("user.dir");
        String jsonPath = baseDir+"/src/jsonToMap/resources/sample.json";
        //convert json map to Map
        Map jsonMap = getMapFromJson(jsonPath);
        System.out.println(jsonMap);
       
    }

    private static Map getMapFromJson(String filePath){
        Gson gson = new Gson();
        JsonReader reader = null;
        try {
            reader = new JsonReader(new FileReader(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return gson.fromJson(reader, Map.class);
    }

}

Also, the sample.json file contains the JSON map under the directory provided.

//sample.json
{
  "text":"first text",
  "digit":1234,
  "boolean":true
}

In the above example, first, it will read the JSON file using JsonReader and we used Gson to convert to Map.

If you want to convert the file which contains the JSON list to List, you can provide the class to convert as below.
//sample.json
[
  {
    "text":"first text",
    "digit":1234,
    "boolean":true
  },
  {
    "text":"second text",
    "digit":1234,
    "boolean":true
  },
  {
    "text":"third text",
    "digit":1234,
    "boolean":true
  }
]


/JsonConverter.java
private static List getListFromJson(String filePath){
        Gson gson = new Gson();
        JsonReader reader = null;
        try {
            reader = new JsonReader(new FileReader(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return gson.fromJson(reader, List.class);
    }
If you want to convert to Custom class, create a class compatible with the fields from the JSON file and provide that class while converting. For e.g:
//sample.json
{
  "text":"first text",
  "digit":1234,
  "aBoolean":true
}


//Sample.java
public class Sample {

    private String text;
    private Double digit;
    private Boolean aBoolean;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Double getDigit() {
        return digit;
    }

    public void setDigit(Double digit) {
        this.digit = digit;
    }

    public Boolean getaBoolean() {
        return aBoolean;
    }

    public void setaBoolean(Boolean aBoolean) {
        this.aBoolean = aBoolean;
    }
}


//JsonConverter.java
private static Sample getSampleFromJson(String filePath){
        Gson gson = new Gson();
        JsonReader reader = null;
        try {
            reader = new JsonReader(new FileReader(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return gson.fromJson(reader, Sample.class);
    }
Here, we pass the class Sample while converting from the JSON. Make sure your JSON file and class structure match.



Share: