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<>();
userSet.add("Alex");
userSet.add("Brian");
userSet.add("Charles");

Gson gson = new Gson(); 

String jsonString= gson.toJson(userSet);  

System.out.println(jsonString);

Program output.

["Alex","Brian","Charles"]

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;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

Gson gson = new Gson(); 

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

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

System.out.println(userSet);

Program output.

["Alex","Brian","Charles"]

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

Happy Learning !!

References:

GSON Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.