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

时间:2023-08-14 21:00:50

前提:已搭建好环境

1.建立Controller

 package com.ice.controller;

 import com.ice.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping("/person")
@Controller
public class PersonController {
@RequestMapping("/get")
@ResponseBody
public Person get(){
Person person=new Person();
person.setAge(18);
person.setName("ice");
return person;
}
}

访问后报错,如下

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

 <mvc:annotation-driven>
<mvc:message-converters>
<!--返回普通字符串-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

3.重新运行ok

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