[java] 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.

This question is related to java json gson

The answer is


Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

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

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel


I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON


I used JSONObject as shown below in Servlet.

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

The Servlet returns this JSON object as shown below:

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

This Servlet is called from Browser using AngularJs as below

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

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to gson

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ Gson library in Android Studio how to parse JSON file with GSON Convert Map to JSON using Jackson "Expected BEGIN_OBJECT but was STRING at line 1 column 1" Representing null in JSON Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 How to parse JSON Array (Not Json Object) in Android Parsing JSON array into java.util.List with Gson Using GSON to parse a JSON array