Avoid type safety warning after deserializing recursive map <String, Object> with Jackson
I am getting recursive logic from REST API which I import in Java as 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);
Then I try to do this in a tree for some attributes, with code like
if (response.get("infos") instanceof Map<?,?>)
Map<String, Object> infos = (Map<String, Object>) response.get("infos");
I am getting a type safety warning when migrating to a card. Quite understandable. Is there any better way than adding @SuppressWarnings("unchecked")
here to tell the compiler that everything will work fine?
source to share
as per fge's comment, the Jackson JsonNode type is the correct way to go.
JsonNode responseAsTree = OBJECTMAPPER.readTree(responseAsString);
JsonNode has all the methods you need to traverse the tree easily. See a quicker XML guide
source to share
In your case, response
is Map<String, Object>
. You are calling response.get("infos")
. From the generators provided, this returns Object
which needs to be mapped to a Map and so you get a warning.
What you can do is not use Map<String, Object>
but define classes that represent the structure of your JSON response.
Something like
public class Response {
private Infos infos;
}
public class Infos {
private int foo;
private String bar;
}
You can then use Jackson to parse the response in that class structure and access all properties using getters / setters, ensuring that your code is type safe.
source to share