GSON – Serialize and deserialize JSON to Set

Learn to use Google GSON library to deserialize or parse JSON to Set (e.g. HashSet) in java. Also, learn to serialize Set to JSON.

It’s worth mentioning that we shall make extra effort only when Set is root element. Gson handle the sets as members (under root) pretty well.

1. Serialize Set to JSON

Java program to serialize HashSet to JSON using Gson.toJson() method.

Set<String> userSet = new HashSet<>();

Gson gson = new Gson(); 

String jsonString= gson.toJson(userSet);  


Program output.


2. Deserialize JSON to Set

Java program to deserialize JSON to HashSet using Gson.fromJson() method and TypeToken.

import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

String jsonString = "['Alex','Brian','Charles','Alex']";

Gson gson = new Gson(); 

Type setType = new TypeToken<HashSet<String>>(){}.getType();

Set<String> userSet = gson.fromJson(jsonString, setType);  


Program output.


Drop me your question related to parse and deserialize json to set in Java.

Happy Learning !!


GSON Github

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.