Why is Spring Object Mapper adding ‘Map’ to Json Response

Last modified date

Comments: 0

Contents

Problem

Recently I experienced a problem in Spring where the Json response returned from the Controller in my Spring Boot Application was nesting my Json response when I was using Object Mapper.

Instead of returning the Json I was expecting, Spring was nesting my Json response in an outer attribute called Map like this:

Expected Json:

{
  "Attribute 1": "Value 1",
  "Attribute 2": "Value 2",
  "Attribute 3": "Value 3",
  "Attribute 4": "Value 4"
}

Actual Json:

"Map": {
    "Attribute 1": "Value 1",
    "Attribute 2": "Value 2",
    "Attribute 3": "Value 3",
    "Attribute 4": "Value 4"
  }

As you can see, my Json is being nested within an attribute called Map.

Solution

The reason that this happens was due to a configuration I had added to my object mapper object.

I was using the WRAP_ROOT_VALUE config to added a nest name to my Json strings, but I didn’t realise that this had an unintended side effect of nesting my Json even when there was no root value.

objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

The default root value is the class name of the type of object you are wrapping.

i.e. if you have a Map, the Java class name for maps is Map, hence why object mapper was wrapping the json with this name.

Take a look at this example below:

Map map = new HashMap();
map.put("Attribute 1", "Value 1");
map.put("Attribute 2", "Value 2");
map.put("Attribute 3", "Value 3");

ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(map);

System.out.println("Unwrapped");
System.out.println(json);

objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

String wrappedJson = objectMapper.writeValueAsString(map);

System.out.println("Wrapped");
System.out.println(wrappedJson);


OUTPUT:

Unwrapped
{"Attribute 1":"Value 1","Attribute 3":"Value 3","Attribute 2":"Value 2"}

Wrapped
{"HashMap":
  {"Attribute 1":"Value 1","Attribute 3":"Value 3","Attribute 2":"Value 2"}
}

As you can see when adding the WRAP_ROOT_VALUE config, it changes the Json output to nest it in HashMap.

The solution to this problem is to either remove the WRAP_ROOT_VALUE configuration or create a new instance of object Mapper

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.