I have a java REST endpoint with POST method and saving a document to a collection in MONGO DB
My entity class is as below:
Employee{
@Id
private ObjectId id;
private Instant startDate;
private Instant endDate;
private String status;
}
As part of POST method, I will be persisting the request Json into the Employee collection.
@BodyParser.Of(BodyParser.Json.class)
public Result postEmployee(Http.Request request) {
final JsonNode requestJson = request.body().asJson();
Gson gson = GsonUtil.getGson();
Employee employee = gson.fromJson(String.valueOf(requestJson), Employee.class);
morphia.datastore().save(employee, new InsertOptions()
.writeConcern(WriteConcern.MAJORITY));
}
I am sending the POST payload as below:
{
"startDate": {"$date":"2023-12-14T09:35:58.325Z"},
"endDate": null,
"status": "IN-PROGRESS"
}
With the above POST implementation code, after mapping the requestjson to Employee, The start Date is being converted to default date 1970-01-01 00:00:00.000Z and the same is getting saved to the collection in the database.
Can someone please let me know how to exactly convert the date mentioned in the payload to the entity and save it in the db.
My startDate field in database should be in this sample format : 2024-01-01 05:48:04.812Z
I tried changing the date format being sent in payload as below but it didnt resolve my issue
{
"startDate": {"$date":"2023-12-14 09:35:58.325Z"},
"endDate": null,
"status": "IN-PROGRESS"
}
I have tried sending the startDate as String and then convert to Instant before saving but Im getting the below error as it is defined as Instant in the model
PersistenceException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING