Search code examples
jsonajaxservletshttprequeststruts

How to read a Json object from HttpServletRequest?


I'm sending a json object from a ajax call to java.

$.ajax({
    cache: false,
    url: 'AddPPCheques.ws',
    type: "POST",
    contentType: "application/json",
    dataType: "json",
    data: "chequesList=" + JSON.stringify(myJson),
    success: function (data) {

    }
}
);

Browser Console ->

chequesList=[{"Bank Code":"4234-322","Cheque No":"23432232","Amount":"432432","Commission":"427","Today":"2018-06-08"},{"Bank Code":"4234-112","Cheque No":"778787","Amount":"8986787","Commission":"2323","Today":"2018-06-08"}]

In java side im trying to read it from a HttpServletRequest.

public ActionForward addCheques(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

    JSONObject myResponse = new JSONObject ( request.getParameter("chequesList").toString() );

}   

But I get a NullPointerException. What am I doing wrong here? And how to read the json object details?


Solution

  • The reason is that you pass the data as JSON but you want to get it as String and invoke toString(),but you will get null so NullPointerException will happen

    So change your ajax code to below:

    $.ajax({
        cache: false,
        url: 'AddPPCheques.ws',
        type: "POST",
        data: {chequesList:JSON.stringify(myJson)},
        success: function (data) {
    
        }
    }
    );