After publishing over 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
- Getting Started with Java-JSON Serialization & Deserialization
- Mapping of Nested Objects
- Mapping of Arrays and Lists of Objects
- Mapping of Maps
- Mapping of Sets
- Mapping of Null Values
- Automatically Generate POJO Classes from JSON Response
- Mapping of Enums
- Mapping of Circular References
- Generics
- Custom Serialization for Simplification (Part 1)
- Changing the Default Serialization with Custom Serialization (Part 2)
- Custom Deserialization Basics
- Custom Instance Creator
- Customizing (De)Serialization via @JsonAdapter
- Custom Deserialization for Calculated Fields
- On-The-Fly-Parsing With Streams
- ProGuard Configuration
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.5
. If you're using Gradle, add the following line:
implementation 'com.google.code.gson:gson:2.8.5'
If you're using Maven, you can add the following dependency:
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
</dependencies>
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 example26
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": "norman@futurestud.io",
"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(
"Norman",
"norman@futurestud.io",
26,
true
);
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": "norman@futurestud.io",
"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':'norman@futurestud.io','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:
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!