Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson serialization for Java object with Map?

Tags:

java

json

jackson

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"
     }
  ]
like image 281
Jason Chen Avatar asked Aug 19 '14 05:08

Jason Chen


1 Answers

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
} ]
like image 144
Alexey Gavrilov Avatar answered Oct 21 '22 07:10

Alexey Gavrilov