Encoding / Decoding Java Classes as JSON Using Gson

Login | Register

Encoding / Decoding Java Classes as JSON Using Gson

Gson

With the rise in popularity of JavaScript client side frameworks such as AngularJS and Ember.js, returning and accepting JSON data from Java applications has become a much more common process. The Gson library allows conversion between Java objects and JSON in a very simple fashion.

Installing Gson

If you’re a Maven user, installing Gson is simply a matter of adding the appropriate dependency into your pom.xml file. If you’re not a Maven user, the Gson library can be downloaded from the project’s site.

To add the dependency to Maven, add the folllowing into your pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

A Simple Domain Object

To see how Gson can convert to and from JSON, we’ll use a simple Java class that represents a simple Blog post. The blog post has a title, a post date and an array of tags.

public class BlogPost {
    private String title;
    private Date postDate;
    private ArrayList&lt;String&gt;tags = new ArrayList();
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public Date getPostDate() {
        return postDate;
    }
 
    public void setPostDate(Date postDate) {
        this.postDate = postDate;
    }
 
    public void addTag(String tag) {
        tags.add(tag);
    }
 
    @Override
    public String toString() {
        return "BlogPost{"
            + "title=" + title
            + ", postDate=" + postDate
            + ", tags=" + tags + '}';
    }
}

There’s nothing special about this class. There are no annotations required or interfaces that need to be implemented. The class is a basic POJO.

Serializing to JSON

To serialize an object to JSON, we need to instantiate an instance of the Gson object and invoke the .toJson() method of it.

BlogPost post = new BlogPost();
post.setTitle("A new blog post");
post.setPostDate(new Date());
post.addTag("Json");
post.addTag("Gson");
Gson gson = new Gson();
String json = gson.toJson(post);
System.out.println(json);

Executing this code shows the JSON generated for the class

{
  "title":"A new blog post",
  "postDate":"Jul 2, 2014 23:24:41 AM",
  "tags":["Json","Gson"]
}

Looking at this output, we can see that Gson has successfully serialized our class into JSON converting all the class members (including the array) into valid JSON.

Deserializing from JSON to Java Object

Deserializing from JSON into a Java object is similarly straightforward and requires calling the fromJson() method of the Gson class passing in the JSON data and the class name of the object to construct. For example:

BlogPost newPost = gson.fromJson(json, BlogPost.class);
System.out.println(newPost.toString());

Outputs:

BlogPost{title=A new blog post, postDate=Thu Jul 02 23:24:41 BST 2014, tags=[Json, Gson]}

Custom Serializers

Sometimes, Gson doesn’t de/serialize objects in exactly the format required by an application, as can be seen in the above example where the postDate field is serialized as a simple string. In a real application, it would more more likely that dates would need to be formatted in an ISO-8601 date format.

This can be achieved by creating a JsonSerializer, for example:

public class DateSerializer implements JsonSerializer&lt;Date&gt; {
    @Override
    public JsonElement serialize(Date date, Type type, JsonSerializationContext jsc) {
        TimeZone tz = TimeZone.getTimeZone("UTC");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(tz);
        return new JsonPrimitive(sdf.format(date));
    }
}

This deserializer could then be called from Gson as follows:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
Gson dateGson = gsonBuilder.create();
String dateJson = dateGson.toJson(post);
System.out.println(dateJson);
{
  "title":"A new blog post",
  "postDate":"2014-07-02T22:24:41+0000",
  "tags":["Json","Gson"]
}

About

At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x