Search code examples
javajacksonoption-typevavr

How to not write Option.None with jackson objectMapper (and read it)?


I use jackson ObjectMapper to serialize and deserialize some data of mine, which have fields of javaslang Option type. I use JavaslangModule (and Jdk8Module). And when it write the json, Option.None value fields are written as null.

To reduce the json size and provide some simple backward compatibility when later adding new fields, what I want is that:

  1. fields with Option.None value are simply not written,
  2. missing json fields that correspond to data model of Option type, be set to Option.None upon reading

=> Is that possible, and how?

Note: I think that not-writing/removing null json fields would solve (1). Is it possible? And then, would reading it works (i.e. if model field with Option value is missing in the json, set it None?


Solution

  • Luckily there is a much simpler solution.

    1) In your ObjectMapper configuration, set serialization inclusion to only include non absent field:

      @Bean
      public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModules(vavr());
        objectMapper.setSerializationInclusion(NON_ABSENT);
    
        return objectMapper;
      }
    

    2) Set the default value of your optional fields to Option.none:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Foo {
      private Option<String> bar = Option.none(); // If the JSON field is null or not present, the field will be initialized with none
    }
    

    That's it!

    And the even better news is that it works for all Iterables, not just for Option. In particular it also works for Vavr List type!