Reputation: 147
in my database I have user with ObjectId("5f78cd195a52a201fb117175").
Then I send it by Spring REST Controller to Angular Frontend and there my object id looks like this:
{date: 1601752345000, timestamp: 1601752345}
Afterwards in frontend I create product object, which contains field userId whose value is set to {date: 1601752345000, timestamp: 1601752345}
. That object is sent to backend and later on is saved in db. The problem is that when it is converted by Jackson in Rest controller the userId field has value ObjectId("5f78cd19065ece5ade441e7a").
So from user with ObjectId("5f78cd195a52a201fb117175") I receive ObjectId("5f78cd19065ece5ade441e7a") I dont have user with this second ObjectId so the field with userId contains no realtion to real user.
DO you know why it happens and how to deal with it ?
Upvotes: 2
Views: 1028
Reputation: 38625
Jackson
treats all objects like POJO
types. By default, serialises all getter
-s. Let's assume, that ObjectId
instance in Java
is represented by org.bson.types.ObjectId which has two getter
-s:
date
field in JSON
timestamp
field in JSON
These two fields will be serialised to JSON
payload. Deserialisation process needs constructor and setters. I guess, in this case constructor ObjectId(int timestamp, int counter) will be chosen (but I am not sure). You can try to create new instance of ObjectId
using this constructor with values from your JSON
payload.
When you use Jackson
to serialise/deserialise types from 3-rd party libraries you can expect that there is a module implemented for this. Take a look on MongoJack:
Since MongoDB uses BSON, a binary form of JSON, to store its documents, a JSON mapper is a perfect mechanism for mapping Java objects to MongoDB documents. And the best Java JSON mapper is Jackson. ...
You need to register this module and serialisation/deserialisation processes should work as expected.
See also:
Upvotes: 1