How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class

Last updated
App Shah

Crunchify » JSON Tutorials » How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class

Convert JSON to XML using Gson and JAXB.

As many of you know already Gson is a great Java library that can be used to convert Java Objects into their JSON representation. It works also in reverse order deserializing the specified JSONObject or JSONArray into an object of the specified class.

How to convert Java object to / from JSON (Gson)?

Basically – this same tutorial will help you if you want to convert gson fromjson to map, gson fromjson to list, json fromjson to array, json string to arraylist in java.

In this tutorial we will go over below steps:

  1. Read File content from file in Java
  2. We will use regex split operation to bypass any blank space in between words
  3. Create JSONObject out of each line
  4. Add each JSONObject to JSONArray
  5. Print JSONArray
  6. Now using Gson’s fromJson() method we will deserialize JSONArray to ArrayList

In order to run below code you need below Maven dependency.

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

Also, here is a file which we are using in below program.

https://crunchify.com/wp-content/uploads/code/crunchify-gson.txt

Please download and put it under C: drive or Documents folder and update path below.

Java code:

package crunchify.com.tutorials;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;

/**
 * @author crunchify.com 
 * Gson() -> fromJson() to deserializes the specified Json into an object of the specified class
 */

public class CrunchifyGoogleGSONExample {

	public static void main(String[] args) {
		JSONArray array = readFileContent();
		convertJSONArraytoArrayList(array);
	}

	private static void convertJSONArraytoArrayList(JSONArray array) {

		// Use method fromJson() to deserializes the specified Json into an object
		// of the specified class
		final ArrayList<?> jsonArray = new Gson().fromJson(array.toString(), ArrayList.class);
		log("\nArrayList: " + jsonArray);

	}

	private static JSONArray readFileContent() {
		JSONArray crunchifyArray = new JSONArray();
		String lineFromFile;

		try (BufferedReader bufferReader = new BufferedReader(new FileReader("/Users/appshah/Documents/crunchify-gson.txt"))) {

			while ((lineFromFile = bufferReader.readLine()) != null) {
				if (lineFromFile != null && !lineFromFile.isEmpty()) {
					JSONObject crunchifyObject = new JSONObject();
					log("Line: ==>" + lineFromFile);

					// escape any blank space between tokens
					String[] split = lineFromFile.split("\\s+");
					crunchifyObject.put("companyName", split[0]);
					crunchifyObject.put("address", split[1]);
					crunchifyObject.put("description", split[2]);
					crunchifyArray.put(crunchifyObject);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("\nJSONArray: " + crunchifyArray.toString());
		return crunchifyArray;

	}

	private static void log(Object string) {
		System.out.println(string);
	}
}

Output:

Line: ==>crunchify.com  NewYork        Java&Blogging
Line: ==>Google.com     MountainView        SearchEngine
Line: ==>Facebook.com      SanJose          SocialMedia
Line: ==>Twitter.com          SanFrancisco         TweetTweet

JSONArray: [{"address":"NewYork","companyName":"crunchify.com","description":"Java&Blogging"},{"address":"MountainView","companyName":"Google.com","description":"SearchEngine"},{"address":"SanJose","companyName":"Facebook.com","description":"SocialMedia"},{"address":"SanFrancisco","companyName":"Twitter.com","description":"TweetTweet"}]

ArrayList: [{address=NewYork, companyName=crunchify.com, description=Java&Blogging}, {address=MountainView, companyName=Google.com, description=SearchEngine}, {address=SanJose, companyName=Facebook.com, description=SocialMedia}, {address=SanFrancisco, companyName=Twitter.com, description=TweetTweet}]

Here is a Google Gson Goal from official Github Repository:

2 thoughts on “How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class”

Leave a Comment