将复杂的json对象发送到Spring MVC控制器 [英] Send complex json object to Spring MVC controller

查看:79
本文介绍了将复杂的json对象发送到Spring MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个复杂的对象发送到spring mvc搜索引擎的ajax控制器,其中包含3个变量:当前页面,每页项和搜索参数.问题在于,使用controller方法的声明不会将params变量视为Map.

I am trying to send a complex object to ajax controller for spring mvc search engine, with 3 variables: the current page, items per page and the search parameters. The problem is that with the declaration of the controller method does not take me the params variable as a Map.

因为我可以分别发送结构以在控制器上收集3个变量?

As I can send the structure to collect on the controller 3 variables separately?

错误:

不存在必需的地图参数"params"

Required Map parameter 'params' is not present

  var dataToSend = {
        'page': 1,
        'itemsPerPage': 10,
        'params': {
          'codItem': "10",
          'nameItem': "foo"
        }
      };  

      $.ajax({
        url: form.attr("action"),
        type: 'POST',
        data: JSON.stringify(dataToSend),
        dataType: 'json',
        cache: false
      }).success(function(data) {
        callback(data);
      });        




 public @ResponseBody HashMap<String, Object> search(@RequestParam(value="params") Map<String, String> params, @RequestParam(value = "page") int page, @RequestParam(value = "itemsPerPage") int itemsPerPage){
};

推荐答案

要正确执行此操作,您需要使用JSON库.春天与杰克逊捆绑在一起.

To do this properly you need to use JSON library. Spring is bundled with Jackson.

首先,您需要创建代表您的JSON的类.

First you need to create class to represent your JSON.

public class MyJson {
  int page;
  int itemsPerPage;
  Map<String, String> params;

  public MyJson() {}

  ... getters/setters

}

您需要更改$ .ajax,发送像这样的数据{data:JSON.stringify(dataToSend)},因为需要参数,所以需要一个名称.

You need to change $.ajax, send data like this { data : JSON.stringify(dataToSend)}, becouse parameter need, a name.

在您的控制器方法中编写以下内容:

In your controller method write this:

ObjectMapper mapper = new ObjectMapper();

// readValue(youStringJson, destinactionClass)
MyJson json = mapper.readValue(data, MyJson.class);

如果您有MyJson params字段的getter,则可以遍历json.getParams()映射.

If you have getter for MyJson params field you can iterate over json.getParams() map.

这篇关于将复杂的json对象发送到Spring MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆