How to Convert JSON to Map Object in Java

Convert JSON to Map Object in Java

In this example program, you will learn simple program about, How to Convert JSON to Map Object in Java. The step by step flow of the program are attached below.

Project Structure

How to Convert JSON to Map Object in Java

Input JSON File (data.json)

{
	"1":"One",
	"2":"Two",
	"3":"Three",
	"4":"Four",
	"5":"Five",
	"6":"Six",
	"7":"Seven",
	"8":"Eight",
	"9":"Nine",
	"10":"Ten"
}

Converting JSON to Map Object (ConvertJSONToMap.java)

package com.dineshkrish.json;

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

import com.google.gson.Gson;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class ConvertJSONToMap {

	public static void main(String[] args) {

		// defining the Gson object
		Gson gson = new Gson();

		// json file
		File jsonFile = new File("input/data.json");

		try {

			// defining FileReader object passing file
			FileReader reader = new FileReader(jsonFile);

			// Convert JSON to Map Object
			Map<Integer, String> map = gson.fromJson(reader, Map.class);
			
			System.out.println(map);

		} catch (FileNotFoundException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}
}

Output

{1=One, 2=Two, 3=Three, 4=Four, 5=Five,
6=Six, 7=Seven, 8=Eight, 9=Nine, 10=Ten}

References

1. Java File Class
2. Java FileReader Class
3. Java GSON Class

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.