I am using Jackson version 2.16.1 and have encountered a peculiar behavior. According to the API documentation, it is recommended to use a common ObjectMapper instance. However, I observe different serialization results when using a shared instance versus a new instance. I have reproduced this issue with a simple example.
public class First {
@JsonUnwrapped(prefix = "")
final Thrid thrid = new Thrid();
}
public class Second {
@JsonUnwrapped(prefix = "fromSecond")
final Thrid thrid = new Thrid();
}
public class Thrid {
@JsonUnwrapped(prefix = "fromThird")
final Common common = new Common("1", "2");
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Common {
public String getA() {
return a;
}
public String getB() {
return b;
}
String a;
String b;
public Common() {
}
public Common(String a, String b) {
this.a = a;
this.b = b;
}
}
public static void main(String[] args) throws JsonProcessingException {
First first = new First();
Second second = new Second();
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(first));
System.out.println(objectMapper.writeValueAsString(second));
System.out.println(new ObjectMapper().writeValueAsString(second));
}
Output--
{"fromThirda":"1","fromThirdb":"2"}
{"fromThirda":"1","fromThirdb":"2"}
{"fromSecondfromThirda":"1","fromSecondfromThirdb":"2"}
The output of the last two lines should be the same, but this is not the case. It appears that the @JsonUnwrapped annotation’s previous value for the Third class is being cached somewhere.
public class First {
@JsonUnwrapped(prefix = "")
final Thrid thrid = new Thrid();
}
If I use a non-empty string instead of an empty one in the above class, the results are consistent.
Can someone please help us with this?
3