0

I'm new bee working on passing below data from jquery to Servlet. Below are my files

javascript:

<script type="text/javascript"> 
function getData(tableName) 
{
    var tableId =tableName+"Table";
    jsonObj = [];
    $(\'#' + tableId + '\').find(\'tbody>tr\').each(function (i) { 
        var $tds = $(this).find('td'), setvilId = $tds.eq(1).text(),setvilNotes = $tds.eq(8).text(); 
        item = {};
        item["id"] = setvilId;
        item["notes"] = setvilNotes;
        jsonObj.push(item); 
    });
    console.log(jsonObj);
    var jsonString =JSON.stringify(jsonObj);
    request(jsonString);
};
</script>

<script type=\"text/javascript\">
function updateNotes () { 
    var editable = true; 
    var editables = $('td[id*=notestd], td[id*=eta]');
    editables.attr('contentEditable', editable);
} 
function request(jsonString) {
    $.ajax({ 
        url: "/updatesetvil", 
        type: "POST",
        data: jsonString, 
        dataType: "text", 
        success: function(){ 
            alert(\"success\");
        }, 
        error:function(){ 
            alert(\"failure\"); 
        } 
    });
};
</script>


Servlet:

public class UpdateSetvil extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

     List<SetvilJsonAttributes> setvilAttrs = new LinkedList<SetvilJsonAttributes>();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Inside servlet");

        // 1. get received JSON data from request
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String json = "";
        if(br != null){
            json = br.readLine();
        }
        System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
        // 2. initiate jackson mapper
         ObjectMapper mapper = new ObjectMapper();

         // 3. Convert received JSON to Class
        SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);

        // 4. Set response type to JSON
        response.setContentType("application/json");

        setvilAttrs.add(setvilatt);

        for (int i=0;i< setvilatt.size(); i++) {
            System.out.println(setvilatt.get(i).getId());
        }
    }
    private class SetvilJsonAttributes {
        Integer id;
        String notes;
        String eta;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getNotes() {
            return notes;
        }

        public void setNotes(String notes) {
            this.notes = notes;
        }

        public String getEta() {
            return eta;
        }

        public void setEta(String eta) {
            this.eta = eta;
        }

    }
}

Error: java.io.IOException: Error parsing JSON request string

I kindly request anyone to help me on this.I have been stuck and unable to proceed further.

4 Answers4

0

try this,

$.ajax({ 
    url: "/updatesetvil", 
    type: "POST",
    // The key needs to match your method's input parameter (case-sensitive).
    data: { jsonString: jsonString},
    contentType: "application/json; charset=utf-8"      
    dataType: "text", 
    success: function(data){ 
        alert(\"success\"+data);
    }, 
    error:function(){ 
        alert(\"failure\"+data); 
    } 
});
hari
  • 1,874
  • 1
  • 16
  • 10
0

Suggestion

If you are getting issues while parsing a JSON string then I can help you to parse the JSON string into Java object using GSON library as illustrated in below sample code.

Please note id should be String otherwise it will result into NumberFormatException for empty id values.

Sample code:

class SetvilJsonAttributes {
    private String id;
    private String notes;
    // getter & setter
}

String jsonString="[{\"id\":\"\",\"notes\":\"\"},{\"id\":\"18001\",\"notes\":\"fdafd\"},{\"id\":\"8350\",\"notes\":\"daggda\"},{\"id\":\"8056\",\"notes\":\"gfdagdfa\"}]";

Type type = new TypeToken<ArrayList<SetvilJsonAttributes>>() {}.getType();
ArrayList<SetvilJsonAttributes> data = new Gson().fromJson(jsonString,type);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

output:

[
  {
    "id": "",
    "notes": ""
  },
  {
    "id": "18001",
    "notes": "fdafd"
  },
  {
    "id": "8350",
    "notes": "daggda"
  },
  {
    "id": "8056",
    "notes": "gfdagdfa"
  }
]

If you don't want to change the type of id field then you can try with JsonDeserializer to deserializer it as per your need.

Please have a look at my another posts here and here for JsonDeserializer.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

See these three lines:

    System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
    ObjectMapper mapper = new ObjectMapper();
    SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);

The value of json is a JSON array. But, then you map it to SetvilJsonAttributes, which does not support JSON array. You can convert this json to a List of SetvilJsonAttributes using:

    ObjectMapper mapper = new ObjectMapper();
    ArrayList<SetvilJsonAttributes> setvilatt = mapper.readValue(json, new TypeReference<ArrayList<SetvilJsonAttributes>>(){});
fajarkoe
  • 1,543
  • 10
  • 12
0

I have used JSONArray and it worked out

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Inside servlet");
        Connection connector = MysqlConnector.getDBCon();
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            json = sb.toString();
        } catch (Exception e) {
            System.out.println("Exception while reading JSON String");
            e.printStackTrace();
        }
        System.out.println("String is " + json);
        try {
            JSONArray inputArray = new JSONArray(json);
            for (int i=0; i < inputArray.length(); i++) {
                JSONObject c = inputArray.getJSONObject(i);
                String id = c.getString("id");
                String notes = c.getString("notes");
                System.out.println(id + "--> " + notes);
        } catch (JSONException e) {
            // crash and burn
            System.out.println("Parse exeception for array");
            e.printStackTrace();
        }
}