Creating json object in javascript and sending it to servlet

14,099

Solution 1

On the Java side of things you need to convert the JSON array to a Java POJO bean first to be able to (easily) do something with it. There are multiple APIs to do this; Google GSON and Jackson are two possibilities.

Jackson is used internally by Jersey, the reference implementation of the JAX-RS API; it works very well in my experience.

Solution 2

What you build isn't a "JSON object", but a plain javascript object.

You must encode your object in JSON :

var param = '?objarray=' + JSON.stringify(arrayOfObjects);
$.ajax({
     url: '/ProjectName/finalXmlServGen'+param,
     type: 'POST', 
     dataType: 'json',  
     success: function(result) {
       alert('SUCCESS');
     }
});

Or you may let jQuery do the encoding :

$.ajax({
     url: '/ProjectName/finalXmlServGen',
     type: 'POST', 
     dataType: 'json',
     data: {objarray: arrayOfObjects}
     success: function(result) {
       alert('SUCCESS');
     }
});
Share:
14,099
shabbir.rang
Author by

shabbir.rang

Updated on June 04, 2022

Comments

  • shabbir.rang
    shabbir.rang almost 2 years

    i am creating json object to save data and then sending it to the servlet. But when i try to retrieve the object and display its contents in java servlet, it throws me an error saying " A JSONObject text must begin with '{' at 1 [character 2 line 1]". I do not know how to display the json object in java which is been sent from javascript. Here's what i am doing:

    Javascript Code:

    var arrayOfObjects = [];
    arrayOfObjects.push({"divid":imageinc,"xCordinates":Xcord,"yCordinates":Ycord,"Height":canvasWidth,"Width":canvasHeight, "PageNo":pageNum});
    

    Displaying Javascript contents:

    for (var i = 0; i < arrayOfObjects.length; i++) {
    var object = arrayOfObjects[i];
    for (var property in object) {
        alert(property + '=' + object[property]);
    }
    }
    

    Sending object to servlet with jquery Ajax:

        var param = 'objarray=' +arrayOfObjects;
    
        $.ajax({
          url: '/ProjectName/finalXmlServGen',
          type: 'POST', 
          dataType: 'json',  
          data: param,
          success: function(result) {
              alert('SUCCESS');
          }
        });
    

    I get success message once i call the ajax. Now, i am receiving this object in servlet as:

    String objarray = request.getParameter("objarray").toString();
    try {
            JSONObject jsonObj = new JSONObject(objarray);          
    
            String xmlString= XML.toString(jsonObj);
            System.out.println("JSON to XML: " + xmlString);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    

    The message i see in my console is the error " A JSONObject text must begin with '{' at 1 [character 2 line 1]". How do i parse the object and form an xml or string?

  • shabbir.rang
    shabbir.rang over 11 years
    doing this it gets me this error "404 (Servlet default is not available)" var param = 'objarray=' + JSON.stringify(arrayOfObjects); $.ajax({ url: '/ProjectName/finalXmlServGen', data: param, This works fine. I get success message. But in servlet i still receive the error that "{" part is missing. Thanks
  • shabbir.rang
    shabbir.rang over 11 years
    Thats perfectly ok. Worked. Now how do i print this object in my java file? Thanks