spring入門(四) spring mvc返回json結果

前提:已搭建好環境html

1.創建Controller

 1 package com.ice.controller;
 2 
 3 import com.ice.model.Person;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.ResponseBody;
 7 
 8 @RequestMapping("/person")
 9 @Controller
10 public class PersonController {
11     @RequestMapping("/get")
12     @ResponseBody
13     public Person get(){
14         Person person=new Person();
15         person.setAge(18);
16         person.setName("ice");
17         return person;
18     }
19 }

訪問後報錯,以下java

Type Exception Report
Message No converter found for return value of type: class com.ice.model.Person
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
    org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.ice.model.Personweb

    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:226)spring

2.解決方法

引入依賴

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

修改spring-configure.xml

 1 <mvc:annotation-driven>
 2         <mvc:message-converters>
 3             <!--返回普通字符串-->
 4             <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
 5             <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
 6                 <property name="supportedMediaTypes">
 7                     <list>
 8                         <value>text/html;charset=UTF-8</value>
 9                         <value>application/json;charset=UTF-8</value>
10                     </list>
11                 </property>
12             </bean>
13         </mvc:message-converters>
14     </mvc:annotation-driven>

 

3.從新運行ok

{"age":18,"name":"ice"}json

相關文章
相關標籤/搜索