在Controller中:
@RequestMapping(value="/login",method=RequestMethod.POST) public @ResponseBody User login(String username,String password){ User user = userService.login(username, password); return user; }
@ResponseBody會自動將user轉化為json字符串
spring-mvc.xml文件:
<!-- 用於將對象轉換為 JSON -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
這里我使用的jackson包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
若是利用hibernate等orm工具生成的pojo類,一對一,對多等關系可能會輸出無限循環的json:
需要使用在pojo類中導入com.fasterxml.jackson.annotation.JsonIgnore,並為需要屏蔽的類添加@JsonIgnore注解,這樣被注解的屬性就不會出現在json中了。
