spring入门 spring mvc返回json结果
Posted ICE_Inspire
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring入门 spring mvc返回json结果相关的知识,希望对你有一定的参考价值。
前提:已搭建好环境
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"}
以上是关于spring入门 spring mvc返回json结果的主要内容,如果未能解决你的问题,请参考以下文章