The code below produces the following compiler warning:
JSONObject obj = new JSONObject();
obj.put("foo", "bar");
Compiler message:
unchecked call to put(K,V) as a member of the raw type java.util.HashMap
I populate the JSONObject with values via JSONObject.put() and then call obj.toString() to get the json out. How can I fix the warning above (I compile with -Werror).
The JSONObject is from the following library.
import org.json.simple.JSONObject;
Maven dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
The json-simple library is compiled with an old bytecode version: 46.0. This is Java 1.2. The JSONObject map extends java.util.HashMap and you are directly using the "put" method of java.util.HashMap
Generics were added in Java 5. Since Java 5, compiler encourages usage of generic types. This way, the compiler suggests, that you should upgrade your code to be more type safe.
In this case, the unsafe usage comes from a library and you have no control over it. I suggest to either search for a newer version of the library or to switch to another library.
Update: you can try following library as an alternative:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Usage:
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("hello", "world");
obj.put("collection", new JSONArray(Arrays.asList(1, "two", Collections.singletonMap("three", 30))));
System.out.println("obj.toString() = " + obj.toString());
}
}
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