Search code examples
javajsonserializationjacksonfasterxml

Jackson Custom serializer for custom behaviour of some fields while having default behaviour for rest of the fields


For example I have a POJO defined as below with jackson-core and jackson-databind (version 2.8.3) annotations omitting getters and setters for brevity.

class Sample {
     private String foo;
     private String bar;
     private Map<String, Map<String, Object>> data;
}

and I would like to write a custom serializer that takes above POJO and generates

{
     "foo":"val",
     "bar":"val2",
     "data_1": {
          "someInt":1
     },
     "data_2": {
          "someBoolean":true
     }
}

Here data_1 and data_2 are keys of main Map and their inner attributes are made up of their sub map (nested map). Also, the actual property data shouldn't be present in resulting JSON at all.

Please note that foo and bar are example of fields, actually the pojo has 15+ fields.


Solution

  • I figured out a simpler way to do this without using the custom serializer; It was with @JsonAnyGetter and @JsonAnySetter. Here is a complete example. I am pasting an answer with respect to sample pasted here as it might be useful for others.

    class Sample {
         private String foo;
         private String bar;
    
         private Map<String, Map<String, Object>> data = new LinkedHashMap<>();
    
         @JsonAnyGetter
         public Map<String, Map<String, Object>> getData() {
              return data;
         }
    
         @JsonAnySetter
         public void set(String key, Map<String, Object>) {
              data.put(key, object);
         }
    }
    

    Example