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

Java使用JSONObject创建JSON对象触发404状态码问题求助

问题产生原因
  • 核心原因是com.google.gwt.thirdparty.json.JSONObject属于Google Web Toolkit(GWT)的客户端专属依赖,设计用于前端代码编译场景,并不适配服务端运行环境,且绝大多数项目不会将该依赖打入服务端部署包。
  • Tomcat运行时加载对应Servlet/接口类时,会抛出ClassNotFoundException或NoClassDefFoundError,导致对应接口的Servlet初始化失败,映射路径未成功注册,因此访问时返回404状态码。
  • 未排查到报错的常见原因是日志配置问题:仅开启了业务日志采集,未捕获Tomcat容器层面的初始化异常,查看Tomcat根目录下logs文件夹中的catalina.out日志即可找到对应的类缺失报错。
JSON创建最优实践

首先明确统一依赖原则:你的项目已经引入了Gson作为JSON处理库,无需额外引入org.json等其他JSON库,混用多类JSON库会增加依赖冲突、版本不一致的风险,统一使用同一款库即可。

1. 基础优化方案(零额外依赖、兼容现有逻辑)

将空返回场景也用Gson处理,避免手动拼接字符串、正则替换的不可靠操作:

import com.google.gson.Gson;
import java.util.Collections;
import java.util.Map;

// Gson是线程安全的,全局复用单例即可,无需每次请求创建新实例
private static final Gson GSON_INSTANCE = new Gson();

// 业务逻辑部分
String json;
if (ymSpecificLineDetail == null) {
    Map<String, String> warningMsg = Collections.singletonMap("empty", "No YM specific lines");
    json = GSON_INSTANCE.toJson(warningMsg);
} else {
    json = GSON_INSTANCE.toJson(ymSpecificLineDetail);
}

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

2. 可维护性优化方案(推荐长期使用)

统一接口返回结构,避免前端兼容多种返回格式,降低前后端对接成本:
首先定义通用响应类:

public class CommonResult<T> {
    // 响应状态码,比如200为成功、500为业务异常
    private int code;
    // 提示信息
    private String message;
    // 响应数据
    private T data;

    // 构造方法、getter、setter略
    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> result = new CommonResult<>();
        result.setCode(200);
        result.setData(data);
        return result;
    }

    public static <T> CommonResult<T> fail(String message) {
        CommonResult<T> result = new CommonResult<>();
        result.setCode(500);
        result.setMessage(message);
        return result;
    }
}

业务逻辑直接复用该结构:

CommonResult<?> result;
if (ymSpecificLineDetail == null) {
    result = CommonResult.fail("No YM specific lines");
} else {
    result = CommonResult.success(ymSpecificLineDetail);
}
String json = GSON_INSTANCE.toJson(result);
// 后续response输出逻辑不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:54:03