Date serialization & deserialization – POJO to JSON (GSON & example)

  • Given the user defined object or POJO, having Date field, we would like to serialize the POJO to JSON.
  • During serialization, we would like save Date as timestamp.
  • We will use the Google gson library to achieve the POJO to JSON conversion and vice versa.
  • We will create Person class and we will perform the following operations with Person class
    1. Convert Person Object to JSON string
      • Serialize the date as timestamp
    2. Convert the JSON string to corresponding person object
      • DeSerialize the timestamp as Date

GSON maven dependency:

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

Program – Date to / from timestamp conversion (POJO <->JSON)

1.) Person Class:

  • The person class containing date data member.
  • We have overloaded toString method to print person information.
package org.learn.gson;
import java.util.Date;
 
public class Person {
    public String firstName;
    public String lastName;
    public Date date;
    public String contact;
    public Person(String firstName, String lastName,
                Date date, String contact) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.date = date;
        this.contact = contact;
    }
    public String toString() {
        return "[" + firstName + " " + lastName +
               " \"" + date.toString() + "\" " +contact +"]";
    }
}

2.) Date2Json Class:

Date2Json is responsible for performing following operations.

  • Convert person object to JSON (serialization).
    • We have written custom DateSerializer class, to serialize date as timestamp.
  • Convert JSON to person object (Deserialization).
    • We have written custom DateSerializer class, to deserialize timestamp as Date.
package org.learn.gson;
import java.lang.reflect.Type;
import java.util.Date;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
 
class DateDeserializer implements JsonDeserializer {
         
    public Date deserialize(JsonElement json, Type typeOfT,
                                    JsonDeserializationContext context)
            throws JsonParseException {
        return json == null ? null : new Date(json.getAsLong());
    }
}
 
class DateSerializer implements JsonSerializer {   
    public JsonElement serialize(Date date, Type typeOfSrc,
                                    JsonSerializationContext context) {
        return date == null ? null : new JsonPrimitive(date.getTime());
    }
}
 
public class Date2Json {
    public static void main(String[] args) {
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(Date.class, new DateDeserializer());
        gson.registerTypeAdapter(Date.class, new DateSerializer());
         
        Gson objGson = gson.setPrettyPrinting().create();
        Person objPerson = new Person("Mike","harvey",new Date(),"00186");
        // Convert Person object to json
        String json = objGson.toJson(objPerson);
        System.out.println("1. Convert Person object to Json");
        System.out.println(json);
 
        // Convert to json to person object
        Type listType = new TypeToken() {}.getType();
        System.out.println("2. Convert JSON to person object");
        Person objFromJson = objGson.fromJson(json, listType);
        System.out.println(objFromJson);
    }
}

Download Sample Code – GSON Object to JSON

Output – Date serialization & deserialization (POJO <-> JSON)

1. <strong>Convert Person object to Json</strong>
{
"firstName": "Mike",
"lastName": "harvey",
<strong>"date": 1454426955623,</strong>
"contact": "00186"
}
2. <strong>Convert JSON to person object</strong>
[Mike harvey <strong>"Tue Feb 02 20:59:15 IST 2016" </strong>00186]