如何通过 RESTful spring 应用程序 return object 的 JSON 表示?

How to return the JSON representation of an object through a RESTful spring application?

我的目标是 Spring 版本 4.2。所以在阅读了 reference documentation, I developed this application.

的一些页面之后

此应用程序只有一种方法。这个方法应该可以return一个JSON表示一个很简单的javaobject。 (部署应用后,可以通过这个URL调用方法:http://localhost:8080/srm/test

相反,我收到以下错误。 (srm 是应用程序的上下文根)

HTTP ERROR 500

Problem accessing /srm/test. Reason:

    Circular view path [test]: would dispatch back to the current handler URL [/srm/test] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
Caused by:

javax.servlet.ServletException: Circular view path [test]: would dispatch back to the current handler URL [/srm/test] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:205)
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:145)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1243)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

我搜索并发现 Spring 为我的控制器方法分配了一个默认查看器。我不确定视图是什么,但在搜索之后,我有点明白 ContentNegotiatingViewResolver 对我来说是正确的。但是在阅读之后,我猜想我必须为我的方法的 @RequestMapping 指定一个 produces 属性 或指定一个 Accept header 用于从我的浏览器发送到我的应用程序的 HTTP 请求。但是 none 成功了!

我在这里要做的就是能够将 return objects 从 RESTful 序列化为 JSON objects Spring 管理的应用程序。我不想使用 Spring 请现在启动。

这是我的文件。 web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>MyAPI</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyAPI</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

MyAPI-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.jarmy.lab.spring.rest" />
</beans>

RESTful 控制器

package com.jarmy.lab.spring.rest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyAPI {

    @RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public MyUser hello() {
        MyUser user = new MyUser();
        user.setName("Abbas");
        user.setId(12);
        return user;
    }
}

一个示例 DTO 将被 return 编辑为响应(采用 JSON 格式)

package com.jarmy.lab.spring.rest;

public class MyUser {
    private String name;
    private long id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

首先,通过将以下代码添加到您的 MyAPI-servlet.xml 来启用基于注释的 MVC:

<mvc:annotation-driven />

因此,您的 MyAPI-servlet-xml 将如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.jarmy.lab.spring.rest"/>
</beans>

然后添加jackson-databind依赖:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.0</version>
</dependency>

添加这个将注册一个 MappingJackson2HttpMessageConverter 转换 to/from JSON。此外,删除您当前的 jackson mapper 依赖项。