我有一个看起来像这样的类:
public class Test {
@JsonProperty("name")
private String name;
public Test(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
还有一个使用 javax.ws.rs 的端点类:
@Path("/Test")
public class Endpoint {
@POST
@Consumes("application/json")
@Produces("application/json")
@HeaderParam("Accept") @DefaultValue("application/json")
public Response createTest(String json) {
return Response.status(Response.Status.ACCEPTED).entity(json).build();
}
}
这按预期工作。
问:如何使 createTest() 将"Test"类作为参数而不是"字符串"?
试用:使用"Test"作为创建Test()的参数时,发送以下内容会给出"415不支持的媒体类型":
POST ../Endpoint/ HTTP/1.1
Host: localhost:8080
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 56d06798-2b32-57fc-c22a-0240aceb8f98
{
"name": "Kalle"
}
我认为你必须使用泽西岛2.xx版本。
public class LoginRequest {
private String userName;
private String password;
public LoginRequest(){
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
您的 Bean 资源(这是您的 Bean 测试)
@POST
@Path("login")
@Consumes(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
....
}
和依赖关系:
<properties>
<jersey.version>2.22.1</jersey.version>
<jackson.version>2.6.1</jackson.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<version>1</version>
<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>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
415 不支持的媒体类型问题的原因是您没有正确的依赖项。
。玩得愉快