Returning JSON response from Servlet to Javascript/JSP page

I think (actually I KNOW!) I'm doing something wrong here I am trying to populate some values into HashMap and add each hasmap to a list which will be added to a JSON object:

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

My problem is I know this is returning a string, which I cannot seem to parse (which is the problem). My question is how do I return the actual JSON encoded string (or even should I be doing this?) or what is the best method of attack for this type of problem. The JavaScript I am using for this is below:

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

Note the JSON Response comes back fine, but its a string. Any advice is greatly appreciated. I am also opening to using googles Gson, but don't have too much knowledge on that.

7
задан Roman C 20 May 2017 в 07:33
поделиться