Gson — Getting Started with Java-JSON Serialization & Deserialization

After publishing close to 50 Retrofit blog posts we've gathered enough feedback that a lot of developers would love an extensive introduction to Google's Gson. Gson is a very powerful library to map data structures represented as JSON to Java objects. Of course, it also supports the other way around and can create an appropriate JSON representation of your Java objects.

If you're interested in where this series is going, 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 Change the Naming of Fields with @SerializedName
  8. Gson Model Annotations — Multiple Deserialization Names 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 (soon)
  17. Gson Builder — How to Ignore Fields with @Expose
  18. Gson Builder — HTML Escaping (soon)
  19. Gson Advanced — Mapping of Enums
  20. Gson Advanced — Mapping of Circular References
  21. Gson Advanced — Generics
  22. Gson Advanced — Custom Serialization for Simplification (Part 1)
  23. Gson Advanced — Changing the Default Serialization with Custom Serialization (Part 2)
  24. Gson Advanced — Custom Deserialization Basics
  25. Gson Advanced — Custom Instance Creator
  26. Gson Advanced — Customizing (De)Serialization via @JsonAdapter
  27. Gson Advanced — Custom Deserialization for Calculated Fields
  28. Gson Advanced — On-The-Fly-Parsing With Streams (soon)
  29. Gson Advanced — ProGuard Configuration (soon)
  30. Practical Gson — Low Level Parsing
  31. Practical Gson — Storing Data in Android's SharedPreferences (soon)
  32. Practical Gson — How to Deserialize a List of Polymorphic Objects
  33. Gson Appendix — 5 Common Mistakes & Issues
  34. Gson Appendix — Overview of Alternatives (soon)
  35. Release of Premium Learning Package

Gson Dependency

This guide will be hands-on and start with some serialization in a minute. Since a lot of our readers are Android developers, we'll tailor it for you, but Gson can be used in any Java environment. Before we can get started, we need to pull in the Gson library to our project. At the time of writing, the latest version is 2.8.0. If you're using Gradle, add the following line:

compile ''  

If you're using Maven, you can add the following dependency:


For the poor guys using neither dependency management system, you can download the jar on the official GitHub repository.

Basics of Java-JSON Serialization

So let's do some serialization! Serialization in the context of Gson means mapping a Java object to its JSON representation. In the next few tutorials our data is going to get more complex, but for now we'll start with a very plain UserSimple object:

public class UserSimple {  
    String name;
    String email;
    int age;
    boolean isDeveloper;

The user object has four properties:

  • The user's name is a String object
  • The user's email is also a String object
  • The user's age is an integer, meaning the age is stored in years (for example 26 and not the exact birthday!)
  • Finally a boolean flag isDeveloper

Our Android or Java application needs to convert a UserSimple object to its JSON representation. Assuming we keep the member names the same, we would expect such a JSON for Norman, the author of this blog post:

  "name": "Norman",
  "email": "",
  "age": 26,
  "isDeveloper": true

So let's see how we can do the conversion with Gson. First of all, we need to create a Java object for Norman:

UserSimple userObject = new UserSimple(  

In order to do the serialization, we need a Gson object, which handles the conversion. We can simply use the constructor:

Gson gson = new Gson();  

Next, we need to call the function toJson() and pass the UserSimple object:

String userJson = gson.toJson(userObject);  

The userJson object contains the following value:

  "age": 26,
  "email": "",
  "isDeveloper": true,
  "name": "Norman"

Gson changed the order of the properties (to alphabetically), but the content is identical! Note how Gson respected the types. String values were wrapped in "", while integer values had no wrapping. We didn't have to mess around with JSON objects or copy single members. A single call to Gson was enough to map the entire object. This comes in extremely handy when we're working with complex data structures. But before going too deep, let's test the other direction. Can Gson create a Java object from the above JSON?

Basics of JSON-Java Deserialization

First of all, we need to create a String, which contains the above-mentioned JSON:

String userJson = "{'age':26,'email':'','isDeveloper':true,'name':'Norman'}";  

We changed the " to ' to avoid tons of \" escaping. Nevertheless, it works either way. The next step is, as you probably have guessed, to create a Gson instance:

Gson gson = new Gson();  

Finally, we've to map from a JSON to a Java object with fromJson():

UserSimple userObject = gson.fromJson(userJson, UserSimple.class);  

Note how we've to pass the expected Java object as the second parameter. Otherwise Gson doesn't know what it should map the JSON to. It's not a magician!

If we attach a debugger and check the resulting userObject it'll show us that Gson successfully mapped all properties correctly:

User Object

Next Steps & Outlook

In this getting started post you've seen the basic usage of Gson. We've shown how easy it is to map from and to JSON data. We're sure you've a bunch of questions at the moment:

  • Do the Java model classes need a constructor/getter/setter?
  • Can the Java model fields be private?
  • How do null values get handled?
  • What if the Java class has different member naming than the JSON?
  • How to (de)serialize arrays/lists of objects
  • How to (de)serialize nested objects
  • Does Gson keep a defined default value for a class property while executing .fromJson() and there isn’t any value for that property available in JSON?

No worries, we'll get to all of them in the upcoming weeks. If you've a specific topic in mind, 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.