JSON响应以文本形式返回

时间:2013-06-04 10:50:22

标签: java json servlets httpresponse

我在java servlet中编写了如下JSON响应,其中JObject是创建的JSON对象

response.setContentType("application/json; charset=UTF-8");
PrintWriter printout = response.getWriter();
printout.print(JObject);
printout.flush();

但它在接收方收到了text / plain

[Server: Apache-Coyote/1.1, ETag: W/"XXXXXXXXXX", Last-Modified: Tue, 04 Jun 2013 10:42:31 GMT, Content-Type: text/plain, Content-Length: 2573, Date: Tue, 04 Jun 2013 10:44:01 GMT]

如何获得准确的JSON响应? 如果我在同一台机器上编写JSON响应,即可获取JSON数据。但是,如果我在另一台服务器中撰写JSON响应,则返回text/plain

这是JObject

JSONObject JObject = new JSONObject(); 
JObject.put("Response", "1"); 
JObject.put("Message", "Client unauthorized"); 

4 个答案:

答案 0 :(得分:6)

我不确定您在servlet中的代码到底是什么。但是我已经创建了一个示例Servlet,并使用相同的代码返回Json输出。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter printout = response.getWriter();

        JSONObject JObject = new JSONObject(); 
        JObject.put("Response", "1"); 
        JObject.put("Message", "Client unauthorized"); 

        printout.print(JObject);
        printout.flush();
            // Or
            // printout.write(JObject.toString()); 
    }

我在浏览器上输出{"Message":"Client unauthorized","Response":"1"}

以下是拍摄结果:

enter image description here

答案 1 :(得分:1)

response.getWriter().write(jsonObj.toString())正在为我工​​作。

答案 2 :(得分:0)

我使用Gson

Gson gson = new Gson();
String jsonData = gson.toJson(student);//here student is object
PrintWriter out = response.getWriter();
try {
    out.println(jsonData);
} finally {
    out.close();
}

答案 3 :(得分:0)

如果您使用的是Java 7的try-with-resources,请确保设置

response.setContentType("application/json");

在try-with-resources之前,因为如果事后进行设置,它将事先关闭PrintWriter,并且不会设置任何contentType。然后,如果它通过Nginx服务器,可能会在发现标头中未设置任何内容时将contentType设置为纯文本,这正是我的问题。

这样做:

response.setContentType("application/json");

try (PrintWriter out = response.getWriter()) {
    out.println(jsonData);
} 

这不是

try (PrintWriter out = response.getWriter()) {
    out.println(jsonData);
} 
// does not set contentType anymore because writer has been flushed already.
response.setContentType("application/json");