Cast Java Object into Java Map<String,Object> Cast Java Object into Java Map<String,Object> json json

Cast Java Object into Java Map<String,Object>


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