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

2021-05-23 19:31

阅读:525

标签:new   map   import   type   serve   person   event   lib   ota   

前提:已搭建好环境

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.解决方法

引入依赖

        
        dependency>
            groupId>com.alibabagroupId>
            artifactId>fastjsonartifactId>
            version>1.2.47version>
        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-8value>
 9                         value>application/json;charset=UTF-8value>
10                     list>
11                 property>
12             bean>
13         mvc:message-converters>
14     mvc:annotation-driven>

 

3.重新运行ok

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

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

标签:new   map   import   type   serve   person   event   lib   ota   

原文地址:https://www.cnblogs.com/ICE_Inspire/p/9734473.html


评论


亲,登录后才可以留言!