GSON Format Date in JSON object
You can globally specify how to format dates in JSON objects using GSON. Very easy, you will only have to declare your custom date once. GSON Format Date method setDateFormat()
witch takes an int a pattern or dateStyle and timeStyle which are both primitive int
types.
Maven dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.memorynotfound.json.gson</groupId>
<artifactId>format-date</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<gson.version>2.3.1</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
</project>
Object to be Serialised/Deserialised
package com.memorynotfound.json;
import java.util.Date;
public class Product {
private long id;
private String name;
private Date created;
private double amount;
public Product(long id, String name, Date created, double amount) {
this.id = id;
this.name = name;
this.created = created;
this.amount = amount;
}
}
GSON Format Date in JSON object
You can call setDateFormat()
multiple times, but only the last invocation will be used to decide the serialization format. The date format will be used to serialize and deserialize Date
, Timestamp
and Date
.
DateFormat
class. Here you will find options like: FULL
, LONG
, MEDIUM
, SHORT
and DEFAULT
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;
public class FormatDate {
public static void main(String... args){
Product product = new Product(1, "Playstation 4", new Date(), 499.99);
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
String result = gson.toJson(product);
System.out.println(result);
}
}
Output
{"id":1,"name":"Playstation 4","created":"26/12/2014","amount":499.99}
Thank you so much! Nice post.