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

时间:2011-05-27 16:01:44

标签: java json gson

我认为(实际上我知道!)我在这里做错了我试图将一些值填充到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响应很好,但它是一个字符串。任何意见是极大的赞赏。我也开始使用谷歌谷歌,但对此没有太多的了解。

3 个答案:

答案 0 :(得分:29)

搞定了!我应该构建一个JSONArray JSONObject个,然后将数组添加到最终的“地址”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

答案 1 :(得分:2)

我在Servlet中使用了JSONObject,如下所示。

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

Servlet返回此JSON对象,如下所示:

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

使用AngularJs从浏览器调用此Servlet,如下所示

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

此代码有效,它在警告对话框中显示正确的数据:

Data.header.status:成功

Data.header.FailureReason:无

Data.header.DetailElements:2

Data.Elements:Coma分隔的字符串值,即NhAdminTree,userName

答案 2 :(得分:1)

我认为您想要做的是将JSON字符串返回到XMLHttpRequest中的对象 - 对吗?

如果是这样,您需要eval字符串将其转换为JavaScript对象 - 请注意,这可能是不安全的,因为您相信JSON字符串不是恶意的,因此执行它。最好你可以使用jQuery的parseJSON

相关问题