Gson — Mapping of Sets

Datetime:2016-08-23 03:11:03          Topic:          Share

In the last two blog posts, we've shown you how to maplist data andJava 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

  1. Getting Started with Java-JSON Serialization & Deserialization
  2. Mapping of Nested Objects
  3. Mapping of Arrays and Lists of Objects
  4. Mapping of Maps
  5. Mapping of Sets
  6. Mapping of Null Values
  7. Gson Model Annotations — How to Ignore Fields with @Expose
  8. Gson Model Annotations — How to Change the Naming of Fields with @SerializedName
  9. Gson Builder — Basics & Naming Policies
  10. Gson Builder — Force Serialization of null Values
  11. Gson Builder — Exclusion Strategies
  12. Gson Builder — Relax Gson with Lenient
  13. Gson Builder — Special Values of Floats & Doubles
  14. Gson Builder — Model Versioning
  15. Gson Builder — Formatting of Dates & Custom Date/Time Mapping
  16. Gson Builder — Pretty Printing
  17. Gson Builder — HTML Escaping

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("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:


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 thelist/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:


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!