问题
I have composed JSON response as below in my java servlet, where JObject is the JSON object created
response.setContentType("application/json; charset=UTF-8");
PrintWriter printout = response.getWriter();
printout.print(JObject);
printout.flush();
But it got received as text/plain in the receiving side
[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]
How to get the exact JSON response?
If i compose the JSON
response in same machine, im getting the JSON data. But if i compose the JSON
response in another server, its returning back as text/plain
.
And this is the JObject
:
JSONObject JObject = new JSONObject();
JObject.put("Response", "1");
JObject.put("Message", "Client unauthorized");
回答1:
I am not sure whether exactly what code you have in the servlet. But I have created a sample Servlet and it returned the Json output with the same above code.
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());
}
And I got {"Message":"Client unauthorized","Response":"1"}
as output on the browser.
Here is the result snap shot:

回答2:
response.getWriter().write(jsonObj.toString())
is working for me.
来源:https://stackoverflow.com/questions/16915916/json-response-is-returning-as-text