Gson – Serialize and Deserialize a 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 member fields, pretty well.

1. Serialize a Set to JSON

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

Set<Item> itemSet = Set.of(new Item(1, "item1"), new Item(2, "item2"), new Item(3, "item3"));

String json = new Gson().toJson(itemSet);

System.out.println(json);

Program output.

[{"id":2,"name":"item2"},{"id":1,"name":"item1"},{"id":3,"name":"item3"}]

2. Deserialize JSON to Java Set

Java program to deserialize JSON to HashSet using Gson.fromJson() method and TypeToken. We are deserializing the JSON string generated in the previous section.

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

Set<Item> items = new Gson().fromJson(json, setType);

System.out.println(items);

Program output.

[Item[id=3, name=item3], Item[id=2, name=item2], Item[id=1, name=item1]]

Drop me your question about parsing and deserializing JSON to set in Java.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
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.