Using Custom DateFormat

In this post, under JSONB, I will explain how to use custom date format when serializing/deserializing Java object containing date information to json format.

By default JSONB when converting date information to json it prints in the format as shown below

2019-02-16T07:16:38.537Z[UTC]

We can change this format globally, globally meaning the custom format will be applied to all objects that are serialized and deserialized using Jsonb instance, created using the custom date format.

Below is an example

Main Code


1  import java.util.Date;
2  
3  import javax.json.bind.Jsonb;
4  import javax.json.bind.JsonbBuilder;
5  import javax.json.bind.JsonbConfig;
6  
7  public class JsonbDemo11 {
8   public static void main(String[] args) {
9       JsonbConfig jsonbConfig = new JsonbConfig();
10      jsonbConfig.withFormatting(true);
11      Jsonb jsonb = JsonbBuilder.create(jsonbConfig);
12      
13      Student student = new Student();
14      student.setId(1);
15      student.setName("John");
16      student.setRollnum(1);
17      student.setDateOfAdmission(new Date());
18      
19      String result = jsonb.toJson(student);
20      System.out.println(result);
21      
22      jsonbConfig.withDateFormat("yyyy MM dd", null);
23      jsonb = JsonbBuilder.create(jsonbConfig);
24      
25      result = jsonb.toJson(student);
26      System.out.println(result);
27  }
28 }

At line 11, we create a Jsonb instance with default date format. As a result when Student instance with date information is serialized, Jsonb instance serialize the date information as shown below

“dateOfAdmission”: “2019-02-16T07:16:38.537Z[UTC]”

Next at line 23, we create another instance of Jsonb with custom date format. The custom date format to be used is set in jsonbConfig as shown at line 22.

Next we serialize the same student instance using the new Jsonb instance and the date is serialized as shown below

“dateOfAdmission”: “2019 02 16”

In this way we can change the date format and specify our own format for serializing/deserializing java objects containing date information.

Below is the complete output

Output


{
    "dateOfAdmission": "2019-02-16T07:16:38.537Z[UTC]",
    "id": 1,
    "name": "John",
    "rollnum": 1
}

{
    "dateOfAdmission": "2019 02 16",
    "id": 1,
    "name": "John",
    "rollnum": 1
}

Leave a Reply