【发布时间】:2016-10-21 05:36:30
【问题描述】:
-------------通用类型------
public class Pair<KT, VT> {
private KT key;
private VT value;
public Pair() {
}
public Pair(KT key, VT value) {
this.key = key;
this.value = value;
}
}
-------------Restful API------------
@Path("/test")
public class TestApi {
@GET
@Path("/query")
@Produces(MediaType.APPLICATION_JSON)
public Pair query(@DefaultValue("0") @QueryParam("key") int key) {
return new Pair(key, "value:" + key);
}
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public String create(Pair<Integer, String> pair){
return "put success : " + pair.toString();
}
}
-------------问题--------------
GET 的响应:http://localhost:8080/api/test/query 是:
{"key":{"type":"int","value":0},"value":{"type":"string","value":"value:0"}}
但是,当我使用“Content-Type: application/json”标头将相同的 json 发布到 POST : http://localhost:8080/api/test/post 时,会发生异常:
谁能告诉我如何发布一个泛型类型对象?
---------------pom.xml-------
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.23.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>9.0.6.v20130930</jetty.version>
</properties>
【问题讨论】:
-
你发帖怎么样?您是否提供“Content-Type: application/json”标头?
-
是的!我已经设置了“Content-Type:application/json”标题。
标签: java json rest generics jersey-2.0