0

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

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
  • what I see is "null" is mapped to 0 by default, or you need value other than 0? – samabcde Feb 12 '23 at 14:24
  • I'm not a 100% sure, as I only used basic Jackson until now, but i guess adding an extra deserializer for Integer.class could work? – Sebastian Feb 12 '23 at 14:25
  • @samabcde, from experience, string "null" is not mapped to 0. value causes exception – Sharon Ben Asher Feb 12 '23 at 15:03
  • I tried this in springboot application and it prints `null 0`. `Person p = objectMapper.readValue(new StringReader(""" { "name": "null", "age": "null" } """), Person.class); System.out.println(p.name + " " + p.age);` – samabcde Feb 12 '23 at 15:39

1 Answers1

-1

To register a Jackson Converter globally, you can either embed it into a deserializer, or into an annotation introspector. For more details and examples, see

https://enji.systems/2023/03/16/jsonb-adapter-jackson-converter.html