Posted In: GSON, JSON

How to map date format using Gson

Use Case – I want to map particular date format to Gson while converting date string to POJO

Maven – Gson

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

Solution

GsonBuilder().setDateFormat()

package com.example.json;

import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonDateformat {
	Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

	public static void main(String[] args) throws Exception {
		GsonDateformat gsonDateformat = new GsonDateformat();
		gsonDateformat.dateformat();
	}

	public void dateformat() throws Exception {
		String json = "{\"birthDate\":\"1976-09-08\"}";
		Reader reader = new StringReader(json);
		Employee4 employee = gson.fromJson(reader, Employee4.class);
		System.out.println(employee);
	}
}

class Employee4 implements Serializable {
	private Date birthDate;

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	@Override
	public String toString() {
		return "Employee2 [birthDate=" + birthDate + "]";
	}
}

Tags:

by , on December 4th, 2018