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

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.