初学 Spring MVC 想试着写个 REST api 返回一个 json , Spring 版本 4.2.4 ,按照官方文档以下配置
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</list>
</property>
</bean>
Controller 的部分
@Controller
@RequestMapping("/")
public class HelloController {
@RequestMapping("/hello")
public String helloMvc() {
return "hello";
}
@RequestMapping("/json")
public @ResponseBody Person getPerson() {
return new Person(123, "Tom", "aaa");
}
}
在 tomcat 上运行结果, jsp 能正常显示, json 却报以下错误
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unrecognized Type: [null]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
看意思是参数错误,但并不知道是为什么。。完整 demo 见 https://github.com/sparetire/demo/
望各位大大解答,感谢!
1
saximoer 2016-02-25 00:31:20 +08:00
有配置 message-converters 么?
|
2
ewBuyVmLZMZE 2016-02-25 00:46:02 +08:00
<dependency>
<groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.5</version> </dependency> 修改版本号,降级。回答完毕。 |
3
ewBuyVmLZMZE 2016-02-25 00:48:07 +08:00 1
如果想用 2.7.x 版本的 Jackson ,那么 Spring 的版本请高于 4.3.x 。
|
4
HunterPan 2016-02-25 08:38:16 +08:00
我直接用 fastJson
|
8
HunterPan 2016-02-25 09:33:13 +08:00
@Sparetire
Element : message-converters Configures one or more HttpMessageConverter types to use for converting @RequestBody method parameters and @ResponseBody method return values. Using this configuration element is optional. HttpMessageConverter registrations provided here will take precedence over HttpMessageConverter types registered by default. Also see the register-defaults attribute if you want to turn off default registrations entirely. |
9
reeco 2016-02-25 09:36:22 +08:00
fastjson 的 message-converters 配置参考:
https://github.com/1994/ssm-scaffold/blob/master/src/main/resources/mvc-dispatcher-servlet.xml |
10
ewBuyVmLZMZE 2016-02-25 09:54:42 +08:00 via iPhone
@reeco 之前有过类似的想法,最后还是放弃了,默认的就好。
|
11
beneo 2016-02-25 09:56:34 +08:00
关键词 @RestContoller
|