jackson serialization for Java object with Map?

13,088

You can use the @JsonAnyGetter annotation on a getter method that returns the map of optional values. Please refer to this blog plost that explains that in details.

Here is an example:

public class JacksonAnyGetter {

    public static class myClass {
        final String Id;
        private final Map<String, Object> optionalData = new LinkedHashMap<>();

        public myClass(String id, String key1, Object value1, String key2, Object value2) {
            Id = id;
            optionalData.put(key1, value1);
            optionalData.put(key2, value2);
        }

        public String getid() {
            return Id;
        }

        @JsonAnyGetter
        public Map<String, Object> getOptionalData() {
            return optionalData;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<myClass> objects = Arrays.asList(
                new myClass("book-id1", "type", "book", "year", 2013),
                new myClass("book-id2", "type", "book", "year", 2014)
        );
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objects));
    }

}

Output:

[ {
  "id" : "book-id1",
  "type" : "book",
  "year" : 2013
}, {
  "id" : "book-id2",
  "type" : "book",
  "year" : 2014
} ]
Share:
13,088
Admin
Author by

Admin

Updated on June 06, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a Java class like this and want to convert to JSON using Jackson. Thanks for your help.

    1. Java Class

      public class myClass {
         String Id;
         Map<String, Object> optionalData = new LinkedHashMap<String, Object>();
      }
      
    2. How to serialization it to JSON using Jackson ObjectMapper ?

    For example, suppose the optionalData is a Map saving two entries <"type", "book"> and <"year", "2014"> I want the output to be as follow. Please note that the key/value of optionalData could be changed on the fly (so, I cannot create a "static" Java object for this without using Map)

      [ 
        { 
          id: "book-id1",
          type: "book",
          year: "2014"
        },
        { 
          id: "book-id2",
          type: "book",
          year: "2013"
         }
      ]
    
  • Jurass
    Jurass almost 4 years
    You can't however deserialize json back to object.