0

This is my code:

json = JSON.stringify(jsonObj);

$.ajax({
    type: 'post', 
    url: 'PostStudentMarks',
    async: false,
    data: json, 
    contentType: "application/json",
    dataType: 'json',
    success: function (response) {
        alert("Marks Uploaded");
    },
    error: function(err) {
        console.log(arguments);
    }
});

jsonObj contains data like this

[{
    "student_id": "11204172"
},{
    "course_id": "PHY101",
    "semester": "1",
    "marks": "11"
},{
    "course_id": "CSE401",    
    "semester": "2",
    "marks": "22"
}]

What should be the proper Java code in the servlet to read and iterate through it?Currently I am using org.json.simple. Moreover if I do like

JSONObject jsonObject = new JSONObject(request.getParameter("json"));
JSONArray json = new JSONArray(jsonObject);

It throws an error saying undefined constructor. What is the proper solution for this? Also note that I do not want to use gson.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Unrelated to your issue, but please remove `async: false`. It's really bad practice to use it as it locks the browser UI for the duration of the request – Rory McCrossan Aug 04 '16 at 08:17

1 Answers1

0
  1. You are better to use a java Pojo which will have same property as your json keys contains . eg: student_id,course_id etc.
  2. Then convert the json to your Pojo class accordingly .... Eg:

    • If your json contain objects the convert to simple pojo
    • If your json contains array then you can use array list as well

Eg:

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'gokul'}";
Staff obj = mapper.readValue(jsonInString, Staff.class);
Gokul
  • 931
  • 7
  • 16