Introduction
I am currently working on a project that regularly saves several java objects to a MongoDB database.
This object contains a Date.
Problem
The conversion of java Date to Json Mongo give this:
new Date() -> "Jan 27, 2022, 2:47:24 AM"
But this format does not conform with MongoDB Date. MongoDB is considered as a string instead of a Date.
Affected code
public record DatedPuzzle(Date date, Puzzle puzzle) {
}
List<InsertOneModel<Document>> bulkWrites = puzzles.parallelStream()
.map(puzzle -> new InsertOneModel<>(Document.parse(gson.toJson(puzzle))))
.toList();
Question
How to create an object conforming to Gson’s serialization?
For example:
new Date() -convert with Gson-> "2022-01-27T01:47:24.000+00:00"
Advertisement
Answer
You could create a Gson object not directly but using GsonBuilder and with some configuration, you will achieve the desired result.
Code:
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSXXX")
.create();
System.out.println(gson.toJson(date));
}
Output:
Thu Feb 03 23:18:18 EET 2022 "2022-02-03T11:18:18.650+02:00"
UPDATE:
The disclaimer of the pattern is following:
yYear (e.g.12or2012)MMonth in a yeardDay in a monthhHour of the day,1-12mMinute in an hour,0-59sSecond in a minute,0-59SMillisecond in second,0-999'Escape for text delimiterX– ISO 8601 time zone (-08;-0800;-08:00)
z – General time zone (Pacific Standard Time; PST; GMT-08:00)
Z – RFC 822 time zone (-0800)
Added some additional codes for a much better understanding of the output on Github.
You could check the locale which is used there simply:
System.out.println(Locale.getDefault());
On my machine it is:
en_US