java - 如何在servlet中读取ajax发送的json

我是java新手,在这个问题上苦苦挣扎了2天,终于决定在这里问。

我正在尝试读取 jQuery 发送的数据,以便在我的 servlet 中使用它

jQuery

var test = [
    {pv: 1000, bv: 2000, mp: 3000, cp: 5000},
    {pv: 2500, bv: 3500, mp: 2000, cp: 4444}
];

$.ajax({
    type: 'post',
    url: 'masterpaket',
    dataType: 'JSON',
    data: 'loadProds=1&'+test, //NB: request.getParameter("loadProds") only return 1, i need to read value of var test
    success: function(data) {

    },
    error: function(data) {
        alert('fail');
    }
});

小服务程序

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
   if (request.getParameter("loadProds") != null) {
      //how do i can get the value of pv, bv, mp ,cp
   }
}

非常感谢您提供的任何帮助。

最佳答案

除非您正确发送,否则您将无法在服务器上解析它:

$.ajax({
    type: 'get', // it's easier to read GET request parameters
    url: 'masterpaket',
    dataType: 'JSON',
    data: { 
      loadProds: 1,
      test: JSON.stringify(test) // look here!
    },
    success: function(data) {

    },
    error: function(data) {
        alert('fail');
    }
});

您必须使用 JSON.stringify 将您的 JavaScript 对象作为 JSON 字符串发送。

然后在服务器上:

String json = request.getParameter("test");

您可以手动解析 json 字符串,也可以使用任何库(我推荐 gson)。

https://stackoverflow.com/questions/19568142/

相关文章:

javascript - 通过使用 json 或 html 文件使用 jQuery ajax 自动刷

c# - 具有多态对象数组的 JSON 反序列化

json - REST API 错误代码返回结构

java - 从 HttpResponse 获取 json

javascript - 如何对事件对象进行字符串化?

json - JSON 和 Protocol Buffer 之间是否有标准映射?

javascript - Javascript 中的元组列表

android - 为 Google Analytics 生成配置文件时无法选择其他 Google

c++ - JSON 模式验证

c# - 从 C# 类生成 JSON 模式