小编典典

从Servlet返回JSON响应到Javascript / JSP页面

json

我认为(实际上我知道!)我在这里做错了事,我试图将一些值填充到HashMap中,并将每个hasmap添加到将添加到JSON对象的列表中:

JSONObject json = new JSONObject();
try
{
    Map address;
    List addresses = new ArrayList();

    int count = 15;

    for (int i=0 ; i<count ; i++)
    {
        address = new HashMap();
        address.put("CustomerName"     , "Decepticons" + i);
        address.put("AccountId"        , "1999" + i);
        address.put("SiteId"           , "1888" + i);
        address.put("Number"            , "7" + i);
        address.put("Building"          , "StarScream Skyscraper" + i);
        address.put("Street"            , "Devestator Avenue" + i);
        address.put("City"              , "Megatron City" + i);
        address.put("ZipCode"          , "ZZ00 XX1" + 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());

我的问题是我知道这将返回一个字符串,我似乎无法解析(这是问题)。我的问题是如何返回实际的JSON编码的字符串(甚至应该这样做?),或者针对这种类型的问题的最佳攻击方法是什么?我为此使用的JavaScript如下:

function getReadyStateHandler(req)
{
    // Return an anonymous function that listens to the
    // XMLHttpRequest instance
    return function ()
    {
        // If the request's status is "complete"
        if (req.readyState == 4)
        {
            // Check that a successful server response was received
            if (req.status == 200)
            {
                msgBox("JSON Response recieved...");
                populateDatagrid(req.responseText.toJSON());
            }
            else
            {
                // An HTTP problem has occurred
                alert("HTTP error: " + req.status);
            }
        }
    }
}

请注意,JSON响应可以很好地返回,但是它是一个字符串。任何意见是极大的赞赏。我也愿意使用Google Gson,但是对此没有太多的了解。


阅读 298

收藏
2020-07-27

共1个答案

小编典典

得到它的工作!我应该已经建设JSONArrayJSONObject秒,然后将阵列添加到最终的“地址” JSONObject。请注意以下几点:

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

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + 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());

这可以正常工作并返回有效且可解析的JSON。希望这对以后的人有所帮助。谢谢您的帮助Marcel

2020-07-27