1、在pom中引入jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
2、springmvc中配置handlerAdapter和数据转换器
<!-- 需要在beans中添加这下声明,才能使用p:xxx-->
xmlns:p="http://www.springframework.org/schema/p"
<!-- 配置返回json数据 -->
<!--配置handlerAdaptor-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
p:ignoreDefaultModelOnRedirect="true">
<property name="messageConverters">
<list>
<!--配置转换器-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
3、在controller中使用注解
@RequestMapping("addRole")
@ResponseBody //使用这个注解表示返回json数据,获取直接配置在@Controller下面,还可以吧@Controller和@ResponseBody写成一个注解@RestController
public ResultBean addRole(Role item){
Integer insert = roleService.insert(item);
return new ResultBean(insert);//ResultBean为一个实体对象
}
原文地址:https://blog.csdn.net/qq_28898309/article/details/83352452