Java程式設計師從笨鳥到菜鳥(五十二) 配置檔案實現將返回 POJO 類直接轉換成 json 物件

明割啦發表於2018-08-16

新增依賴

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.4</version>
</dependency>

配置檔案

<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <!--json轉換器-->
            <ref bean="mappingJacksonHttpMessageConverter" />
        </list>
    </property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
    <property name="messageConverters">  
        <list>  
               <ref bean="mappingJacksonHttpMessageConverter" />  
        </list>  
    </property>  
</bean>  

<bean id="mappingJacksonHttpMessageConverter"  
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
     <property name = "supportedMediaTypes">  
          <list>  
            <bean class="org.springframework.http.MediaType">  
             <constructor-arg index="0" value="text"/>  
             <constructor-arg index="1" value="plain"/>  
             <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
            <bean class="org.springframework.http.MediaType">  
             <constructor-arg index="0" value="*"/>  
             <constructor-arg index="1" value="*"/>  
             <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
            <bean class="org.springframework.http.MediaType">  
             <constructor-arg index="0" value="text"/>  
             <constructor-arg index="1" value="*"/>  
             <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
             <bean class="org.springframework.http.MediaType">  
             <constructor-arg index="0" value="application"/>  
             <constructor-arg index="1" value="json"/>  
             <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
          </list>  
    </property>  
</bean>   

後臺直接返回 POJO 物件

原文傳送門:https://blog.csdn.net/gsycwh/article/details/56675836 非常感謝作者

相關文章