JSON and Generics in Java - Type safety warning

If you can't switch to another library or modify the code of this library to make it generic, the only other option would be to write a wrapper around this library which uses it, and properly supports generics.

So you would have your own JSONObject class which would contain an org.json.simple.JSONObject, would extend HashMap<String, Object> and implement Map<String, Object>, and would contain forwarding methods for all the methods of org.json.simple.JSONObject.

You would still have to put @SuppressWarnings("unchecked") in this class, but it would be limited to this class, and all the rest of your code could be free of generic warnings or the suppression of them.


What is your JSONObject, does it inherit from HashMap? If does, the warn probably means that your should declare the JSONObject instance as follows:

JSONObject<String,Object> obj=new JSONObject<String,Object>();

Updated: Look at the definition of the JSONObject:

public class JSONObject extends HashMap

it extends HashMap but doesn't support parameter type, if its definition is

public class JSONObject<K,V> extends HashMap<K,V>

then we could write

JSONObject<String,Object> obj=new JSONObject<String,Object>();

and the put method will no longer generate the warning


public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware

But does not have type parameter in class definition, The only option you have is to add the @SuppressWarnings("unchecked")