如何从 HttpServletRequest 读取 Json 对象?
How to read a Json object from HttpServletRequest?
我正在从 ajax 调用向 java 发送一个 json 对象。
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
contentType: "application/json",
dataType: "json",
data: "chequesList=" + JSON.stringify(myJson),
success: function (data) {
}
}
);
浏览器控制台 ->
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"}]
在 java 这边我试图从 HttpServletRequest 读取它。
public ActionForward addCheques(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject myResponse = new JSONObject ( request.getParameter("chequesList").toString() );
}
但是我得到一个 NullPointerException。我在这里做错了什么?以及如何读取 json 对象详细信息?
原因是您将数据作为 JSON
传递,但您想将其作为字符串获取并调用 toString()
,但您将得到 null,因此会发生 NullPointerException
因此,将您的 ajax
代码更改为以下内容:
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
data: {chequesList:JSON.stringify(myJson)},
success: function (data) {
}
}
);
我正在从 ajax 调用向 java 发送一个 json 对象。
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
contentType: "application/json",
dataType: "json",
data: "chequesList=" + JSON.stringify(myJson),
success: function (data) {
}
}
);
浏览器控制台 ->
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"}]
在 java 这边我试图从 HttpServletRequest 读取它。
public ActionForward addCheques(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject myResponse = new JSONObject ( request.getParameter("chequesList").toString() );
}
但是我得到一个 NullPointerException。我在这里做错了什么?以及如何读取 json 对象详细信息?
原因是您将数据作为 JSON
传递,但您想将其作为字符串获取并调用 toString()
,但您将得到 null,因此会发生 NullPointerException
因此,将您的 ajax
代码更改为以下内容:
$.ajax({
cache: false,
url: 'AddPPCheques.ws',
type: "POST",
data: {chequesList:JSON.stringify(myJson)},
success: function (data) {
}
}
);