6

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"
     }
  ]
Wundwin Born
  • 3,467
  • 19
  • 37
Jason Chen
  • 61
  • 1
  • 1
  • 2

2 Answers2

2

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
} ]
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
0

You need to write your own Jackson JsonSerializer to create custom JSON string from Java object as per the need.

Here are the nice posts along with example


The same thing you can achieve using GSON JsonSerializer

Here are some examples


Here is the code using GSON Serialiser

List<MyClass> list = new ArrayList<MyClass>();

MyClass myClass1 = new MyClass();
myClass1.setId("book-id1");
myClass1.getOptionalData().put("type", "book");
myClass1.getOptionalData().put("year", "2014");
list.add(myClass1);

MyClass myClass2 = new MyClass();
myClass2.setId("book-id2");
myClass2.getOptionalData().put("type", "book");
myClass2.getOptionalData().put("year", "2013");
list.add(myClass2);

class MyClassSerialiser implements JsonSerializer<MyClass> {

    @Override
    public JsonElement serialize(final MyClass obj, final Type typeOfSrc,
            final JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("id", obj.getId());
        Map<String, String> optioanlData = obj.getOptionalData();
        if (optioanlData.size() > 0) {
            for (Map.Entry<String, String> entry : optioanlData.entrySet()) {
                jsonObject.addProperty(entry.getKey(), entry.getValue());
            }
        }

        return jsonObject;
    }
}

String jsonString = new GsonBuilder().setPrettyPrinting().
        .registerTypeAdapter(MyClass.class, new MyClassSerialiser()).create()
        .toJson(list);

System.out.println(jsonString);

output:

[
    {
        "id": "book-id1",
        "type": "book",
        "year": "2014"
    },
    {
        "id": "book-id2",
        "type": "book",
        "year": "2013"
    }
]
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76