Spring MVC Rest服务使用JSON

时间:2016-01-24 22:46:33

标签: java json rest spring-mvc jackson

我正在尝试使用消耗 JSON Spring MVC 创建 Rest API

控制器:

@RestController public class CrawlerController {


@RequestMapping(value = "/checkForMarfeelizableSite", method = RequestMethod.POST)
public ResponseR checkForMarfeelizableSites(@RequestBody List<Entry> list) {

    // Response
    ResponseR responseR = new ResponseR();
    responseR.setOperationResult(OperationResult.OK);

    for (Entry entry : list) {
        System.out.println("Entry: " + entry);
    }

    return responseR;
} }

Entry.class

public class Entry {

String url;

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}}

的web.xml:

<web-app>

<display-name>Marfeel Marfeelizable Checker</display-name>

<!-- Spring Context -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/marfeel-context.xml</param-value>
</context-param>

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<!-- Servlet -->
<servlet>
    <servlet-name>marfeel-crawler-api</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Mapping -->
<servlet-mapping>
    <servlet-name>marfeel-crawler-api</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<!-- Welcome file List -->
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

我在我的pom.xml中添加了 Jackson lib (jackson-mapper-asl),但我收到了HTTP 415 Error

这是我发送的json示例:

[{"url": "c­and­a.com"},{"url": "toshiba.es"}]

1 个答案:

答案 0 :(得分:0)

你能检查以下内容吗?

  • 更改
  

公共ResponseR checkForMarfeelizableSites(@RequestBody 列表   列表)

  

public ResponseR checkForMarfeelizableSites(@RequestBody    ArrayList 列表)

(因为List是一个接口,因此无法创建实例)。

  • Entry.class:在类名上方添加@XmlRootElement,以及一个空承包商(Web可导出类所需)