JSON and Generics in Java - Type safety warning

后端 未结 7 1424
逝去的感伤
逝去的感伤 2020-12-10 05:05

I have some data stored in Java elements and I need to return it in a given format - JSONObject. While my implementation works fine, I\'m still getting a warning message fro

相关标签:
7条回答
  • 2020-12-10 05:17

    You could create a map object and then do an explicit cast to JSONObject

    Map<String, String> obj =  new HashMap<String, String>();
    obj.put("id",way.getId());
    JSONObject jsonObj =  (JSONObject) obj;
    

    But note that this will restrict you only include "Strings" in your JSON. and you will see compile errors if you put another data structure. Say an array.

    0 讨论(0)
  • 2020-12-10 05:20

    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

    0 讨论(0)
  • 2020-12-10 05:27

    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")

    0 讨论(0)
  • 2020-12-10 05:27

    try to change the put line to other

     JsonPath.parse(jsonObj).set(fieldPath, Value);
    
    0 讨论(0)
  • 2020-12-10 05:40

    FYI org.codehaus.jettison.json.JSONObject will not cause this warning. When using codehaus' JSONObject, you also have the ability to catch parsing errors via org.codehaus.jettison.json.JSONException. See https://github.com/codehaus/jettison for details.

    0 讨论(0)
  • Another option is to initialize the JSONObject with a (parameterized) Map<String, Object>. That way, a value can be of any valid JSON type, and you avoid the unchecked warning. E.g.:

    public class WayToJsonConverter{
        ...
        public JSONObject wayToJson(){
            Map<String, Object> forJsonObj = new HashMap<>();
            forJsonObj.put("id",way.getId());  // No warning, hurray!
            forJsonObj.put("integer", 14);
            forJsonObj.put("floating", 1.4);
            JSONObject obj = new JSONObject(forJsonObj);
            ...
            return obj;
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题