Java 创建 JSON 对象导致状态 404

Java creating a JSON object results in a status 404

我正在使用以下方法创建 JSON 警告:

String warningString = "{\"empty\":\"No YM specific lines\"}";
json = new Gson().toJson(warningString);
json = json.replaceAll("^['\"]*", "").replaceAll("['\"]*$", "").replace("\", "");

虽然这行得通,但我发现会有更好的方法:

import com.google.gwt.thirdparty.json.JSONObject;

JSONObject obj = new JSONObject();
try {
    obj.put("empty", "No YM specific lines");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

但是,当我测试时,这会导致状态 404。我检查了日志,没有发现任何错误。我正在使用 Apache Tomcat/9.0.46.

更改为:

import org.json.JSONException;
import org.json.JSONObject;

String json = null;
if (ymSpecificLineDetail == null) {
    //Gracefully return a warning message
        
    json = new JSONObject().put("empty", "No YM specific lines").toString();    
} else {
    json = new Gson().toJson(ymSpecificLineDetail);
}
    
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

将您的导入更改为:

import org.json.JSONException;
import org.json.JSONObject;