Gson — Mapping of Sets

In the last two blog posts, we've shown you how to map list data and Java maps using Gson. In this blog post, you'll learn how to (de)serialize Java Sets.

Of course, this is not the only post in our Gson series. If you're interested in the other topics, check out our series outline:

Gson Series Overview

Serialization of Java Sets

The Java collection framework contains various data structures. We've looked at lists and maps, which have some differences in their JSON representation. This week, we'll look at sets. A HashSet for example is a good way to ensure uniqueness in your data collection. Since sets exist for a reason and are used in the real-world, Gson needs to be able to deal with them as well.

So let's go through a hands-on scenario. Your app has a feature where multiple users can join together as a group. Of course, every user can only join once so we're using a HashSet to store the user names.

If we implement this in Java, we would have something like this:

HashSet<String> users = new HashSet<>();  
users.add("Christian");  
users.add("Marcus");  
users.add("Norman");  
users.add("Marcus"); // would not be added again  

The serialization of sets is the same as with any other type. You can just throw it at Gson and it'll do the correct thing:

Gson gson = new Gson();  
String usersJson = gson.toJson(users);  

This would result in the following JSON:

[
  "Marcus",
  "Christian",
  "Norman"
]

As you can see the JSON representation of a set is identical to that of a list. Yes, Java handles them internally completely different, but on a high level, they both store the same data. For an implementation-agnostic notation like JSON the internal details don't matter.

Deserialization of Java Sets

As we mentioned above, the JSON representation for lists and sets is the same. Thus, Gson is happy to deserialize a valid JSON into either Java data type. Remember our flowerCount example from the list/array blog post? Since we can use the JSON for either one, let's look at it:

[
    {
      "name": "Christian",
      "flowerCount": 1
    },
    {
      "name": "Marcus",
      "flowerCount": 3
    },
    {
      "name": "Norman",
      "flowerCount": 2
    }
]

The way we handle serialization of a set is the same as with lists. We create a Type for Gson and then let it do its magic:

String founderJson = "[{'name': 'Christian','flowerCount': 1}, {'name': 'Marcus', 'flowerCount': 3}, {'name': 'Norman', 'flowerCount': 2}]";

Gson gson = new Gson();

Type founderSetType = new TypeToken<HashSet<Founder>>(){}.getType();

HashSet<Founder> founderSet = gson.fromJson(founderJson, founderSetType);  

The founderSet variable actually holds the same content as a list from the previous blog post, just in a different data type:

Outlook

In this blog post you've seen how you can serialize and deserialize Java sets from and to JSON. You've learned that in the JSON context they're no different from lists. For now we've explored all major data types and will look into some general Gson configuration options next.

If you've feedback or a question, let us know in the comments or on twitter @futurestud_io.

Make it rock & enjoy coding!

Explore the Library

Find interesting tutorials and solutions for your problems.