在java servlet中创建Json响应

问题描述:

我正尝试从java servlet创建一个JSON响应。通过使用一些教程中,我做了在java servlet中创建Json响应

JSONObject json  = new JSONObject(); 
    JSONArray addresses = new JSONArray(); 
    JSONObject address; 
    try 
    { 
     int count = 5; 

     for (int i=0 ; i<count ; i++) 
     { 
      address = new JSONObject(); 
      address.put("CustomerName"  , "Decepticons" + i); 
      address.put("Street"   , "Devestator Avenue" + i); 
      address.put("City"    , "Megatron City" + i); 
      address.put("Country"   , "CyberTron" + i); 
      addresses.add(address); 
     } 
     json.put("Addresses", addresses); 
    } 
    catch (JSONException jse) 
    { 

    } 
    response.setContentType("application/json"); 
    response.getWriter().write(json.toString()); 

和出卖出期权

{"Addresses":[{"CustomerName":"Decepticons0","Street":"Devestator Avenue0","City":"Megatron City0","Country":"CyberTron0"},{"CustomerName":"Decepticons1","Street":"Devestator Avenue1","City":"Megatron City1","Country":"CyberTron1"},{"CustomerName":"Decepticons2","Street":"Devestator Avenue2","City":"Megatron City2","Country":"CyberTron2"},{"CustomerName":"Decepticons3","Street":"Devestator Avenue3","City":"Megatron City3","Country":"CyberTron3"},{"CustomerName":"Decepticons4","Street":"Devestator Avenue4","City":"Megatron City4","Country":"CyberTron4"}]}  

的问题是,当我试图解析为它显示一个错误的

错误解析我的Android应用程序这数据org.json.JSONException: Value <html><head><title>Apache of type java.lang.String cannot be converted to JSONObject

正在使用android代码json解析示例从 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

任何人都可以解决我的问题吗? 在此先感谢。

+0

您的服务器响应不是'json',你有没有尝试登录'JSON = sb.toString();'? – 2012-08-11 10:43:36

+0

我检查http://jsonlint.com/说这是验证json – Kstar 2012-08-11 10:47:10

+0

它看起来像你的服务器(或中间的一些服务器)忽略你的JSON和HTML返回到你的客户端,很可能是一个错误页面。复制应用用户的确切URL并将其粘贴到浏览器(或'curl')中,查看它发生的情况。 – Barend 2012-08-11 10:54:02

尝试的

json.toJSONString() 

代替

json.toString() 
+0

它似乎没有json.toJSONString()预定义的函数。错误说的 - JSONString()的方法未定义为JSONObject类型 – Kstar 2012-08-11 10:43:17