I am using org.eclipse.jetty.util.ajax.JSON to parse JSON text. But the JSON.parse(string) method produces an Object and I need it as a Map. Internally it is an object of exactly the mentioned class. But how do you cast an Object into a Map without constructing a new one or getting the unchecked cast warning?
Currently, I have found only one solution without the unchecked cast warning, but with constructing a new Map, which is actually of course not a casting at all.
private Map<String,Object> getMap(String string) {
HashMap<String,Object> result = new HashMap<>();
Object object = JSON.parse(string);
if (object instanceof Map) {
Map<?,?> map = (Map)(object);
for (Map.Entry<?,?> entry : map.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
result.put(key,value);
}
}
return result;
}
So whether is there a way to properly cast it without unchecked cast warnings?
The compiler can't guarantee that the cast is safe. Since you are the one making the guarantee, you should use @SuppressWarnings("unchecked")
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/SuppressWarnings.html
As @TedHopp points out, the way that library is supposed to be used is that you cast each value in the returnd Object
to the type you know it is (but you would have to cast every property you retrieve) See the mappings here http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/util/ajax/JSON.html
The point that it brings out, is that you are guaranteeing that this JSON object only contains other JSON objects (map to objects)
Therefore, if for some reason you're passed the input
// properties are not quoted for readability
{ a: 2, b : {c:3} }
Your code would fail with an invalid cast exception when you try
map.get("a")
So remember you're the one guaranteeing what goes into that string you're parsing into JSON
If you can't guarantee it, you can't create this getMap function you would like. You have to do the casting (and @SupressWarnings
) at the place that knows what type a specific object is.
For some type safety when working with JSON, you should learn about
Those classes allow you to read JSON directly into Java classes
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