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
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.
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")
try to change the put line to other
JsonPath.parse(jsonObj).set(fieldPath, Value);
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.
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;
}
...
}