欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-06 11:58:13
前提:已搭建好环境 1.建立Controller 访问后报错,如下 Type Exception ReportMessage No converter found for return value of type: class com.ice.model.PersonDescription The ......

前提:已搭建好环境

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