spring入门(四) spring mvc返回json结果

2018-10-03 17:57:41来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

前提:已搭建好环境

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 }

访问后报错,如下

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.Person

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

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"}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:JDK源码学习笔记——HashSet LinkedHashSet TreeSet

下一篇:使用dom4j写xml文件——源码