Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid type safety warning after deserializing recursive Map<String,Object> with Jackson

Tags:

java

jackson

I am getting from a REST API a recursive dictionnary that I import in Java as a Map<String,Object> using Jackson with the following code

  private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
    private static  final MapType GENERICMAPTYPE = OBJECTMAPPER.getTypeFactory().constructMapType(
            Map.class, String.class, Object.class);
...

  Map<String, Object> response =  OBJECTMAPPER.readValue(result.getBody(),GENERICMAPTYPE);

I then try to do down in the tree for some attributes, with code like

   if (response.get("infos") instanceof Map<?,?>)
            Map<String, Object> infos = (Map<String, Object>) response.get("infos");

I get a type safety warning on the cast to Map. Perfectly understandable. Is there a betterway than adding the @SuppressWarnings("unchecked") here to tell the compiler everything will work fine?

like image 338
Yves Nicolas Avatar asked Jun 25 '26 13:06

Yves Nicolas


1 Answers

In your case, response is a Map<String, Object>. You are calling response.get("infos"). From the supplied generics, this returns Object, which has to be cast to Map and this is why you get a warning.

What you can do is to not use a Map<String, Object>, but define classes, that represent the structure of your response JSON.

Something like

public class Response {

    private Infos infos;

}

public class Infos {

     private int foo;
     private String bar;
}

Then, you can use Jackson to parse the response into this class structure and access all properties via getters / setters, ensuring that your code is type-safe.

like image 102
Danail Alexiev Avatar answered Jun 28 '26 01:06

Danail Alexiev