HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Libraries / GSON – Serialize and deserialize JSON to Set

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Gson Tutorial

  • Gson – Introduction
  • Gson – Installation
  • GSON – (De)serialize JSON
  • Gson – Pretty Printing
  • GSON – Array
  • GSON – Set
  • Gson – Map
  • Gson – GsonBuilder
  • Gson – NULL values
  • Gson – Version Support
  • Gson – @SerializedName
  • Gson – Ignore fields
  • Gson – JsonReader
  • Gson – JsonParser
  • Gson – Custom (De)serialization
  • Gson – Quick Guide

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces