How to Convert Set to JSON in Java using GSON API

Convert Set to JSON in Java

In this example, We will show simple example program about, How to convert set to json in java

1) Simple POJO (Plain Old Java Object) Class

package com.dineshkrish.json;

public class Pizza {

	private int pizzaId;
	private String pizzaName;
	private double pizzaPrice;

	public Pizza(int pizzaId, String pizzaName, double pizzaPrice) {

		this.pizzaId = pizzaId;
		this.pizzaName = pizzaName;
		this.pizzaPrice = pizzaPrice;
	}

	public int getPizzaId() {
		return pizzaId;
	}

	public String getPizzaName() {
		return pizzaName;
	}

	public double getPizzaPrice() {
		return pizzaPrice;
	};

}

2) Converting Set Object to JSON String

package com.dineshkrish.json;

import java.util.HashSet;
import java.util.Set;

import com.google.gson.Gson;

public class SetConversion {

	public static void main(String[] args) {

		// Defining Gson Object
		Gson gson = new Gson();
		
		// Defining the set object
		Set<Pizza> set = new HashSet<Pizza>();
		
		set.add(new Pizza(101, "Chicken Pizza", 150));
		set.add(new Pizza(102, "Veg Pizza", 120));
		set.add(new Pizza(103, "Cheese Pizza", 100));
		set.add(new Pizza(104, "Onion Pizza", 80));
		set.add(new Pizza(105, "Pepproni Pizza", 125));
		
		// Convert Set to JSON
		String jsonString = gson.toJson(set);
		
		System.out.println(jsonString);
		
	}
}

Output

[{“pizzaId”:101,”pizzaName”:”Chicken Pizza”,”pizzaPrice”:150.0},
{“pizzaId”:105,”pizzaName”:”Pepproni Pizza”,”pizzaPrice”:125.0},
{“pizzaId”:103,”pizzaName”:”Cheese Pizza”,”pizzaPrice”:100.0},
{“pizzaId”:102,”pizzaName”:”Veg Pizza”,”pizzaPrice”:120.0},
{“pizzaId”:104,”pizzaName”:”Onion Pizza”,”pizzaPrice”:80.0}]

References

1. Java Set API
2. Java HashSet API
3. JSON 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.