Site icon

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

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:

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.

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. Convert Person object to Json
{
"firstName": "Mike",
"lastName": "harvey",
"date": 1454426955623,
"contact": "00186"
}
2. Convert JSON to person object
[Mike harvey "Tue Feb 02 20:59:15 IST 2016" 00186]
Exit mobile version