How to Convert Map to JSON in Java using Gson API

Convert Map to JSON in Java

Simple example about, How to Convert Map to JSON in Java using Gson API.

Item.java

package com.dineshkrish.json;

public class Item {

	private int itemId;
	private String itemName;
	private String itemDesc;
	
	public Item(int itemId, String itemName, String itemDesc) {
		
		this.itemId = itemId;
		this.itemName = itemName;
		this.itemDesc = itemDesc;
	}

	public int getitemId() {
		return itemId;
	}

	public String getitemName() {
		return itemName;
	}

	public String getitemDesc() {
		return itemDesc;
	}

}

MapConversion.java

package com.dineshkrish.json;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

public class MapConversion {

	public static void main(String[] args) {

		// Defining Gson Object
		Gson gson = new Gson();
		
		// Defining Map Object
		Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
		
		// Adding elements to Map
		itemMap.put(101, new Item(101, "Java", "Java Language"));
		itemMap.put(102, new Item(101, "C", "C Language"));
		itemMap.put(103, new Item(101, "Python", "Python Language"));
		itemMap.put(104, new Item(101, "Ruby", "Ruby Language"));
		itemMap.put(105, new Item(101, "Php", "PHP Language"));
		
		// Convert Map to Json
		String jsonString = gson.toJson(itemMap);
		
		System.out.println(jsonString);
		
	}
}

Output

{“102”:{“itemId”:101,”itemName”:”C”,”itemDesc”:”C Language”},”103″:{“itemId”:101,”itemName”:”Python”,”itemDesc”:”Python Language”},”101″:{“itemId”:101,”itemName”:”Java”,”itemDesc”:”Java Language”},”104″:{“itemId”:101,”itemName”:”Ruby”,”itemDesc”:”Ruby Language”},”105″:{“itemId”:101,”itemName”:”Php”,”itemDesc”:”PHP Language”}}

References

1. Gson API JavaDocs

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.