2013-06-04 179 views
1

我在我的Java Servlet,其中JObject是JSON对象创建JSON响应返回文本

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

但它得到了收到的纯文本/在接收端如下组成的JSON响应

[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"); 
+0

我们是在谈论Servlet的? – 2013-06-04 10:53:11

+2

JSON是文本,你必须解析返回的值。 – MasNotsram

+0

提供JObject细节...声明和初始化 –

回答

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

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

+0

令我惊讶的是,printout.print()和printout.write()都可以在所有浏览器中工作。但是,如果我在eclipse IDE中运行它作为'在服务器上运行'运行,它将其作为文本读取。这之前? – John

+0

我也在Eclipse中运行它,它正在工作。这种行为与浏览器无关,因为它在服务器端。至少应答头和响应主体应该是相同的... –