spring mvc接收JSON格式的参数

1.配置spring解析json的库

  <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.8</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
 

2.设置spring mvc 的配置文件

配置中资源解析器,messageConverters属性接收一个list,如果有其他解析器可以依次向其中添加,

不同的请求content类型spring会选择不同的解析器,解析后的内容会通过特殊的注解传送到spring mvc controller的方法中。

<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <util:list>
                <beans:bean id="stringHttpMessageConverter" class="com.weishu.platform.integration.support.spring.ConfigurableStringHttpMessageConverter">
                    <beans:constructor-arg value="UTF-8"/>
                </beans:bean>
               
                <beans:bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
               
            </util:list>
        </beans:property>
    </beans:bean>

3.配置spring mvc controller

使用注解@RequestBody配置参数为json对象,注意目前spring 配合 Jackson JSON库还不能正确处理泛型,如果将@RequestBody DeviceCommand[] deviceCommands 替换为List<DeviceCommand> deviceCommands ,spring 将不能将json解析为DeviceCommand对象,而是转换为LinkedHasMap对象。

 @RequestMapping(value = "/admin/deviceManagement/update_device_white_list_status", method = RequestMethod.POST)
 @ResponseBody
 public String updateUserWhiteListStatus(Model model, @RequestBody DeviceCommand[] deviceCommands) {
  JSONObject result = new JSONObject();
  try {
   deviceService.changeDeviceWhiteListStatus(Arrays.asList(deviceCommands));
   result.put("success", true);
  } catch (Exception e) {
   result.put("success", false);
   result.put("message", e.getMessage());
   e.printStackTrace();
  }
  return result.toJSONString();
 }

4.在请求中设置json对应的content类型

  $.ajax({
    url : ‘update_device_white_list_status.service‘,
    dataType : ‘json‘,
    contentType : ‘application/json‘,
    data : $.toJSON(deviceCommands),
    success : function(e) {
     $.messager.progress(‘close‘);
     if (e.success) {
      whiteListGrid.datagrid("reload");
      $.messager.alert(‘成功‘, ‘操作成功‘, ‘info‘);
     
     } else {
      $.messager.alert(‘请注意‘, ‘操作失败:‘ + e.message, ‘error‘);
     }
    },
    error : function(e) {
     $.messager.progress(‘close‘);
     $.messager.alert(‘请注意‘, ‘操作失败:‘ + e.message, ‘error‘);
    }
   });
时间: 2024-08-25 15:47:46

spring mvc接收JSON格式的参数的相关文章

Spring mvc 返回json格式 - 龙企阁 - 博客频道 - CSDN.NET

第一次使用spring mvc ,在此也算是记录一下以防忘记,希望有经验的朋友指出不足的地方 一.使用maven管理jar. [html] view plaincopyprint? <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.9.6</version> &

spring mvc返回json格式和json字符串

首先有必要说一下,json和json字符串是不一样的,后者是一个字符串.而json是一个对象 当然如果调用位置是后台程序这几乎没有区别,因为在后台,无论什么格式数据,都是从响应流中读取字符串. 但是在前端就有很大区别 没错这是一个字符串, 这个taxs是在上一步保存的. 在看另一个请求 这个就是json对象. 这两种形式,其实就一种区别就是在返回头信息中的Content-Type 如果Content-Type是application/json 则浏览器在接收到对象后自动转换为json对象,如果是

Spring MVC返回json格式

在使用SpringMVC框架直接返回json数据给客户端时,不同的版本有差异. 下面介绍两种类型的版本如何配置. 注意:这两种方法均已验证通过. 1.Spring3.1.x版本 1.1 dispatcher-servlet.xml配置文件如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans&q

Spring MVC 接收多个实体参数

在SpringMVC 的接收参数中,如果接收一个实体对象,只需要在方法参数中这样做:@RequestBody User user //单个的时候这样接收 @RequestMapping(value = "/user/default/save",method = RequestMethod.POST) public ResponseBasicBean saveUserAndMore(@RequestBody User user) { return null; } //批量的时候这样接收

spring接收json格式的多个对象参数(变通法)

如果使用spring mvc同客户端通信,完全使用json数据格式,需要如下定义一个RequestMapping @Controller public class TestController{ @RequestMapping("\test") @ResponseBody public RetureResult test(@RequestBody User user){ return new ReturnResult(); } } 这样,可以将json格式的数据转换为指定的对象user

【spring mvc】后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface

后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Speci

如何让Spring MVC接收的参数可以转换为java对象

场景: web.xml中增加了一个DispatcherServlet配置,并在同级目录下添加了**-servlert.xml文件,搭建起了一个spring mvc的restful访问接口. 问题描述: Controller的@RequestBody, 如果参数定义类型为String,则可以获取到数据; 如果参数定义类型为其他java对象,就接收不到. 下面记录完整的解决方法: 1. web.xml <!-- spring mvc依赖的大环境,此参数会被ContextLoaderListener使

spring mvc接收ajax提交的JSON数据,并反序列化为对象

需求:spring mvc接收ajax提交的JSON数据,并反序列化为对象,代码如下: 前台JS代码: //属性要与带转化的对象属性对应 var param={name:'语文',price:16}; $.ajax({ url: "/book/adddata", type: "POST", dataType: 'json', //必需设定,后台@RequestBody会根据它做数据反序列化 contentType:"application/json&quo

spring mvc接收数组

(一)前言 对于springmvc接收数组的问题啊,我试验过几次,但是了有时候成功了,有时候失败了,也不知道为啥的,然后现在又要用到了,所以打算具体看看到底怎么回事,但是了我实验成功了顺便找了好多资料的. (二)spring mvc接收数组测试代码 @ResponseBody @RequestMapping(value = "/test/array", method = RequestMethod.POST) public JSON test(@RequestParam(value =