JSON响应以文本形式返回 [英] JSON response is returning as text

查看:255
本文介绍了JSON响应以文本形式返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

但它在接收方收到text / plain

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]

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

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.

这是 JObject

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


推荐答案

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

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()); 
    }

我得到了 {消息:客户未经授权的,响应:1} 作为浏览器的输出。

And I got {"Message":"Client unauthorized","Response":"1"} as output on the browser.

以下是结果快照:

这篇关于JSON响应以文本形式返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆