SpringMvc中请求和响应需要用到json格式的数据,那如何使json转换生效呢?
时间: 2024-05-07 07:15:23 浏览: 10
SpringMvc中使用json格式的数据需要依赖Jackson库,需要在配置文件中添加相关依赖和配置。
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
```
2. 配置SpringMvc
在SpringMvc的配置文件中添加以下配置:
```xml
<!--配置Json转换器-->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!--配置RequestMappingHandlerAdapter-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
```
以上配置完成后,就可以在Controller中使用@ResponseBody注解返回json格式的数据了。