Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject unchecked call to put(K,V) as a member of the raw type java.util.HashMap

Tags:

java

json

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>
like image 555
s5s Avatar asked Dec 01 '22 10:12

s5s


1 Answers

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());
    }
}
like image 109
ygor Avatar answered Dec 04 '22 00:12

ygor