How to Convert List to JSON in Java using Gson API

Convert List to JSON in Java

This is a simple program about, How to Convert List to JSON in Java using Gson API. The Gson API can be downloaded from here

Product.java

package com.dineshkrish.json;

public class Product {

	private int productId;
	private String productName;
	private String productDesc;

	public int getProductId() {
		return productId;
	}

	public void setProductId(int productId) {
		this.productId = productId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getProductDesc() {
		return productDesc;
	}

	public void setProductDesc(String productDesc) {
		this.productDesc = productDesc;
	}

}

ListConversion.java

package com.dineshkrish.json;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class ListConversion {

	public static void main(String[] args) {

		Gson gson = new Gson();

		List<Product> list = new ArrayList<Product>();

		// Defining 2 Product Object
		Product p1 = new Product();
		p1.setProductId(101);
		p1.setProductName("Item 1");
		p1.setProductDesc("About Item1");

		Product p2 = new Product();
		p2.setProductId(102);
		p2.setProductName("Item 2");
		p2.setProductDesc("About Item2");

		Product p3 = new Product();
		p3.setProductId(103);
		p3.setProductName("Item 3");
		p3.setProductDesc("About Item3");

		list.add(p1);
		list.add(p2);
		list.add(p3);

		// Covert List to Json
		String jsonString = gson.toJson(list);

		System.out.println(jsonString);

	}
}

Output

[{“productId”:101,”productName”:”Item 1″,”productDesc”:”About Item1″},{“productId”:102,”productName”:”Item 2″,”productDesc”:”About Item2″},{“productId”:103,”productName”:”Item 3″,”productDesc”:”About Item3″}]

References

1. Gson API JavaDoc