话不多说,三部:
一、在pom.xml引入jakcson
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.7</version> </dependency>
注意springmvc的版本,我这边用的是<spring-version>4.3.4.RELEASE</spring-version>
二、在spring的配置文件添加如下注解
<mvc:annotation-driven>
<!-- <mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</mvc:message-converters> -->
</mvc:annotation-driven>
三、在controller请求头上添加@ResponseBody
@RequestMapping(value="get/{id}",method=RequestMethod.GET) @ResponseBody public Area getAreaById(@PathVariable("id") Long id) { Area area = dao.queryAreaById(id); return area; }
这样java对象就能返回json格式数据了.
java对象可以是实体类,集合类等等