Reputation: 189
i have a class that has a UUID
attribute that is being generated in the constructor, so it means it's generated every time a new object is created.
I am using Jackson to deserialize json strings into objects with ObjectMapper
. The issue is that when i deserialize, it deserializes the json string into a new object, and calls the constructor of the class, which results in generating a new UUID
. So basically it takes the Json string that already has a UUID
, and when it deserializes it changes it to a new one.
Any ideas how to solve this using Jackson?
Upvotes: 1
Views: 902
Reputation: 189
The issue was that i had a setter which checked if UUID
was null, and if it was not, it did not set it to the new one. So when the object was created it automatically got a UUID
, and Jackson couldn't set it with the setter since it was not null. When i removed the if
from the setter, it worked fine.
Upvotes: 2
Reputation: 12022
I was not able to reproduce the problem. Below is my code. It works as expected.
public static class MyPojo {
private String id;
public MyPojo() {
this.id = UUID.randomUUID().toString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public static void main(String[] args) throws JsonProcessingException {
var om = new ObjectMapper();
var myPojo = om.readValue(" {\"id\":\"6d1eab11-d64f-4152-9955-3d5c54828cd9\"}", MyPojo.class);
assertThat(myPojo.id).isEqualTo("6d1eab11-d64f-4152-9955-3d5c54828cd9");
System.out.println("id = " + myPojo.id);
}
Upvotes: 1
Reputation: 10964
You could add a second private constructor and annotate this constructor with @JsonCreator
. This will make Jackson use this constructor for de-serialization. You can add additional arguments to the constructor and annotate the arguments with @JsonProperty
- I think - to make Jackson set the respective values correctly.
Upvotes: 1