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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With