JSON response is returning as text

◇◆丶佛笑我妖孽 提交于 2019-12-08 05:57:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!