Spring可以轻易实现在Controller中将一个对象转成Json放在ResponseBody中返回,如下:
@RequestMapping(value = "/getqbankrecord/{qbId}/{id}", method = RequestMethod.GET)
@ResponseBody
public QuestionRecord getQuestionBankRecord(@PathVariable("qbId") int qbId,
@PathVariable("id") int id,
HttpServletRequest request)
{
assert(qbService != null);
this.logger.info("this is getQuestionBankRecord ......");
QuestionRecord record = qbService.getQRecord(qbId, id);
return record;
}
并且在容器中配置messageConverters
<!-- Json -->
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<util:list id="beanList">
<beans:bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<!--
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>text/html;charset=UTF-8</beans:value>
<beans:value>text/json;charset=UTF-8</beans:value>
<beans:value>application/json;charset=UTF-8</beans:value>
</beans:list>
</beans:property>
-->
</beans:bean>
</util:list>
</beans:property>
</beans:bean>
但测试过程中发现一个有趣的问题,一个比较复杂的QuestionRecord类对象转乘Json没有问题,但一个非常简单的TestA类却遇到了如下异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.writeWithMessageConverters(AnnotationMethodHandlerAdapter.java:1050)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.handleResponseBody(AnnotationMethodHandlerAdapter.java:990)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:939)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:438)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
TestA类非常简单,就一个List成员变量
public class TestA {
private List<String> items;
public TestA()
{
items = new ArrayList<String>();
}
public void add(String t)
{
items.add(t);
}
}
开始总以为是Content-Type或者Accept属性有问题,但找了半天原因才发现这里有个基本的要求:POJO对象要转成Json,则要求POJO中的属性必须都有getter方法,加上getter方法后就正常了 :)