Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing into a HashMap of custom objects with jackson

People also ask

What is Jackson's TypeReference?

Class TypeReference<T>This generic abstract class is used for obtaining full generics type information by sub-classing; it must be converted to ResolvedType implementation (implemented by JavaType from "databind" bundle) to be used.

What is Jackson serialization and deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations.

How an object gets Serializaed when used as a key in HashMap?

Hashmap: A HashMap stores items in key/value pairs, and we can access them by an index of another type (such as a string). Now to serialize anything, you have to implement the java. io. Serializable interface and HashMap also implements the Serializable interface.

Does Jackson use Java serialization?

Note that Jackson does not use java.


You should create specific Map type and provide it into deserialization process:

TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);

You can use TypeReference class which does the type casting for map with user defined types. More documentation at https://github.com/FasterXML/jackson-databind/

ObjectMapper mapper = new ObjectMapper();
Map<String,Theme> result =
  mapper.readValue(src, new TypeReference<Map<String,Theme>>() {});

You can make a POJO that extends a Map.

This is important for dealing with nested maps of objects.

{
  key1: { nestedKey1: { value: 'You did it!' } }
}

This can be deserialized via:

class Parent extends HashMap<String, Child> {}

class Child extends HashMap<String, MyCoolPojo> {}

class MyCoolPojo { public String value; }

Parent parent = new ObjectMapper().readValue(json, Parent.class);
parent.get("key1").get("nestedKey1").value; // "You did it!"