How to read complex JSON object from jQuery in Servlet request.getParameter

ぐ巨炮叔叔 提交于 2019-11-29 16:23:11

The data argument of $.ajax() takes a JS object representing the request parameter map. So any JS object which you feed to it will be converted to request parameters. Since you're passing the JS object plain vanilla to it, it's treated as a request parameter map. You need to access the individual parameters by exactly their request parameter name representation instead.

String name1 = request.getParameter("rooms[0][name]");
String capacity1 = request.getParameter("rooms[0][capacity]");
String name2 = request.getParameter("rooms[1][name]");
String capacity2 = request.getParameter("rooms[1][capacity]");
// ...

You can find them all by HttpServletRequest#getParameterMap() method:

Map<String, String[]> params = request.getParameterMap();
// ...

You can even dynamically collect all params as follows:

for (int i = 0; i < Integer.MAX_VALUE; i++) {
    String name = request.getParameter("rooms[" + i + "][name]");
    if (name == null) break;
    String capacity = request.getParameter("rooms[" + i + "][capacity]");
    // ...
}

If your intent is to pass it as a real JSON object so that you can use a JSON parser to break it further down into properties, then you have to convert it to a String before sending using JS/jQuery and specify the data argument as follows:

data: { "rooms": roomsAsString }

This way it's available as a JSON string by request.getParameter("rooms") which you can in turn parse using an arbitrary JSON API.


Unrelated to the concrete problem, don't use $ variable prefix in jQuery for non-jQuery objects. This makes your code more confusing to JS/jQuery experts. Use it only for real jQuery objects, not for plain vanilla strings or primitives.

var $foo = "foo"; // Don't do that. Use var foo instead.
var $foo = $("someselector"); // Okay.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!