You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 14 Spring Boot迁移时JSONObject.keySet()报NoSuchMethodError求助

问题:JSONObject.keySet() 抛出NoSuchMethodError异常

问题背景

我正在将代码从某API迁移至基于Java 14、Spring Boot开发的另一API,编写了如下方法:

public Object getJsonIgnoreCase(JSONObject json, String clave) {
    return json.keySet().stream().filter(k -> k.equalsIgnoreCase(clave))
               .findFirst().map(json::get).orElse("");
}

运行时异常

执行代码时抛出如下错误:

Exception in thread "pool-8-thread-1" java.lang.NoSuchMethodError: 'java.util.Set org.json.JSONObject.keySet()'
    at biz.belcorp.ssicc.leadingconsultant.service.InterfaceGenerateFileTextPlain.getJsonIgnoreCase(InterfaceGenerateFileTextPlain.java:137)
    at biz.belcorp.ssicc.leadingconsultant.service.InterfaceGenerateFileTextPlain.write(InterfaceGenerateFileTextPlain.java:80)
    at biz.belcorp.ssicc.leadingconsultant.service.InterfaceUploadService.uploadFile(InterfaceUploadService.java:164)
    at biz.belcorp.ssicc.leadingconsultant.service.IntGenerInterfaceService.lambda$1(IntGenerInterfaceService.java:230)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at java.base/java.lang.Thread.run(Thread.java:832)

当前依赖配置

项目POM中已声明的json依赖:

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

原因分析

  1. 依赖版本冲突:项目中存在多个版本的org.json库。编译阶段使用的是你声明的20220320版本(该版本包含keySet()方法),但运行阶段加载了其他依赖间接引入的旧版本org.json,而旧版本没有提供keySet()方法。
  2. API版本兼容性:org.json.JSONObject的keySet()方法是在较新版本中才新增的,部分早期版本(如20180813之前的部分版本)不支持该方法。

解决方案

方案1:排查并排除冲突依赖

  • 执行Maven命令查看依赖树,找出所有引入org.json的依赖:
    mvn dependency:tree
    
  • 在POM中对引入旧版本json的依赖添加排除规则,确保仅使用你声明的20220320版本。示例:
    <!-- 假设spring-boot-starter-web间接引入了旧版本json -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    

方案2:替换实现逻辑(不依赖keySet方法)

如果暂时无法解决依赖冲突,可改用旧版本支持的API实现忽略大小写查找键:

public Object getJsonIgnoreCase(JSONObject json, String clave) {
    Iterator<String> keys = json.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key.equalsIgnoreCase(clave)) {
            return json.get(key);
        }
    }
    return "";
}

内容的提问来源于stack exchange,提问作者MarceloChG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:10:07