gpt4 book ai didi

java - JSONObject 未检查调用 put(K,V) 作为原始类型 java.util.HashMap 的成员

转载 作者:行者123 更新时间:2023-11-29 06:26:59 24 4
gpt4 key购买 nike

下面的代码会产生以下编译器警告:

JSONObject obj = new JSONObject();
obj.put("foo", "bar");

编译器信息:

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

我通过 JSONObject.put() 用值填充 JSONObject,然后调用 obj.toString() 来获取 json。我该如何修复上面的警告(我使用 -Werror 进行编译)。

JSONObject 来自以下库。

import org.json.simple.JSONObject;

Maven 依赖:

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>

最佳答案

json-simple 库是使用旧字节码版本编译的:46.0​​。这是Java 1.2。 JSONObject 映射扩展了 java.util.HashMap,您直接使用 java.util.HashMap 的“put”方法

泛型是在 Java 5 中添加的。从 Java 5 开始,编译器鼓励使用泛型类型。这样一来,编译器建议,您应该升级代码以提高类型安全性。

在这种情况下,不安全的使用来自库,您无法控制它。我建议要么搜索更新版本的库,要么切换到另一个库。

更新:您可以尝试使用以下库作为替代方案:

    <dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>

用法:

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());
}
}

关于java - JSONObject 未检查调用 put(K,V) 作为原始类型 java.util.HashMap 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com