无法将JSON发布到Jersey

时间:2016-10-12 16:26:44

标签: json maven tomcat post jersey

我无法获得使用JSON的Jersey服务。我一直收到415不支持的媒体类型错误。这是我的服务类和方法。 GET请求与使用纯文本的POST一样工作,但使用带有JSON的第三个方法的URI进行测试会生成错误。 Jersey内部的文档表示要取消对媒体 - moxy依赖项的注释,以添加我已经完成的JSON功能,但它不会影响行为。我在Tomcat中使用下面的web.xml运行它

package com.example;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("/myresource")
public class MyResource {

@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
    String path = "Got it";
    return "Got it!";
}


@POST
@Path("/testpost/{x}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String testPost (@PathParam("x") String sessId) {
    return "{a: \"333\"}" ;
}

@POST
@Path("/testjson")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String testjsonpost ()
{
    return "{json-received: \"333\"}" ;
}

}

我的maven依赖项是:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
        <!-- artifactId>jersey-container-servlet</artifactId -->
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
    </dependency>

</dependencies>
<properties>
    <jersey.version>2.23.2</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Web.xml中

<web-app version="2.5" 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_2_5.xsd">
<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.example</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/webapi/*</url-pattern>
</servlet-mapping>

1 个答案:

答案 0 :(得分:0)

添加此依赖项

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
</dependency>

它对我有用。