I need to convert certain values in json body of all my http requests.
Specifically, the client will send string "null"
instead of null reference for String
properties and 0
for int
properties.
example json body of request
{
"name": "null",
"age": "null"
}
needs to be deserialized into
public class Person {
public String name; // name == null
public int age; // age == 0
}
Initially I added custom String Deserializer to ObjectMapper:
@Bean
public Module convertNullValueToNullReference() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StdDeserializer<>(String.class) {
@Override
public String deserialize(JsonParser p, DeserializationContext context) throws IOException {
String value = StringDeserializer.instance.deserialize(p, context);
if ("null".equalsIgnoreCase(value)) {
return null;
}
return value;
}
});
return module;
}
but this obviously does not work for the case of int fields. I need to add type converter to ObjectMapper
but there is no addConverter()
method in SimpleModule
.
I know about @JsonDeserialize(converter = ...)
but I need to register the converter globally for all classes.
I searched SO and could only find this related question but the answer is tailored to the specific conversion of dates and is not suitable for my case