I have a Java Spring REST API that receives a JSON string in the body of a POST request. JSON string is large; it contains multiple nested objects.
Upon receiving the POST request, I am converting the string into a DTO object.
Problem
One of the nested object contains a key startDate
that is not being de-serialized correctly.
Value of the startDate
object is:
"startDate": 1622746800000
I have tried de-serializing the string using Jackson
as well as Gson
BUT both of them fail to parse the startDate
correctly.
Exception thrown when using Gson
:
java.text.ParseException: Unparseable date: "1622746800000"
If I pass the startDate
as null
, everything works fine - string is converted into DTO object correctly.
Question
Any idea what could be a possible cause for this problem? How can I fix it?
P.S. Value for startDate
is received as part of a response from the backend. I am sending that same response string to the backend in the POST request body.
Code:
Following is the code that parses the string received in the request's body:
ObjectMapper mapper = new ObjectMapper();
MyDTOClass evData = mapper.convertValue(evDataJsonStr, MyDTOClass.class);
I have tried with Gson
as well:
Gson mapper = new Gson();
MyDTOClass evData = mapper.fromJson(evDataJsonStr, MyDTOClass.class);
Above value when serialized becomes: 1622746800000
and this is what i am trying to de-serialize.
CodePudding user response:
In my understanding Gson
cannot de-serialize epoch time by default. But Jackson
can.
For Jackson you can do the following,
ObjectMapper mapper = new ObjectMapper();
MyDTOClass evData = mapper.readValue(evDataJsonStr, MyDTOClass.class);
Please note that its ObjectMapper's readValue
method not convertValue
method