I have a json string and I want to do some changes to it with the following code in Java using Jackson:
public String transformJson(String json) {
final ObjectMapper mapper = new ObjectMapper();
Student s = mapper.readValue(json, Student.class))
// Do some changes on the object s
return mapper.writeValueAsString(s);
}
Here is the Student class:
@AllArgsConstructor
@Data
@JsonInclude(Include.NON_NULL)
public static class Student {
private String firstName;
private String lastName;
private String country;
private Long age;
}
The code above works and let's suppose the json in input is the following:
{
"firstName" : "Jim",
"lastName" : "Miles"
}
If no change is done, the output would be the same. The annotation @JsonInclude(Include.NON_NULL) would just remove any null field from the output.
But now the new requirement is this: when the input json explicity define a value as null, then the output should show that field as null. That means that when the input is the following:
{
"firstName" : "Jim",
"lastName" : "Miles",
"country" : null
}
Then the output should still be:
{
"firstName" : "Jim",
"lastName" : "Miles",
"country" : null
}
Any idea on how I can achieve this?
AtomicReference, but that's not really elegant. What's the point in having the property with value null? What's the difference between{country: null}and{}?