使用spring @ResponseBody将controller返回值序列化为json格式

1、确保包含jackson-core-asl.jar、jackson-mapper-asl.jar

2、使用的spring mvc的xml配置文件的xsd版本为3.1及以上

3、使用的spring mvc的xml配置文件添加配置:

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:context="http://www.springframework.org/schema/context"  

    xmlns:mvc="http://www.springframework.org/schema/mvc"  

    xmlns:task="http://www.springframework.org/schema/task"  

    xsi:schemaLocation="http://www.springframework.org/schema/beans 

    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 

    http://www.springframework.org/schema/tx 

    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

    http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-3.1.xsd

    http://www.springframework.org/schema/mvc

    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd

    http://www.springframework.org/schema/aop 

    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 

    http://www.springframework.org/schema/task 

    http://www.springframework.org/schema/task/spring-task-3.1.xsd">

  .......

    <mvc:annotation-driven/> 

........

4、代码

/**
* 测试ResponseBody标签: 默认spring mvc会将返回值转换为json格式
* 
* @param request
* @param response
*/
@RequestMapping(value = "/response-body-test", method = RequestMethod.GET)
public @ResponseBody
User testResponseBody(HttpServletRequest request,
HttpServletResponse response) {
User user = new User();
user.setId(11);
user.setName("张三");
user.setOpTime(new Date());
LOG.info("response-body-test execute ok.");
return user;
}

注意:如果启动web容器时spring的xml配置文件load卡住不动,可能是多个spring的xml配置文件的xsd版本不一致导致的。

你可能感兴趣的:(spring)