我有一个端点接受DriverJson
类实例作为http请求有效负载。 DriverJson
类的属性userId
的类型为java.util.UUID
。
问题是Jersey无法将UUID
字符串反序列化为UUID
对象。当我调试并检查driverJson
时,userId1
属性为null
(幸运的是它不会抛出异常)。我已经阅读了这篇文章(article),该文章解释了具有fromString(String string)
方法(java.util.UUID
具有它的类)或具有一个(String
)参数的构造函数的类被Jersey反序列化自动(无需编写任何其他反序列化程序类)。如果我将UUID
类型更改为String
并将其转换为我自己(UUID.fromString(userId)
),那么它的工作效果非常好。
另外,我在一些端点中使用了@PathParam UUID
个参数,它们完美地工作(正如预期的那样)。
以下是我的代码:
我的资源端点:
@POST
public Response add(DriverJson driverJson) {
DriverJson driver = service.add(driverJson);
return Response.status(Response.Status.CREATED).entity(driver).build();
}
我的驱动程序类:
@XmlRootElement
public class DriverJson {
private UUID id;
private String name;
private UUID userId;
public DriverJson() {}
public DriverJson(UUID id, String name, UUID userId){
this.id = id;
this.name = name;
this.userId = userId;
}
/// getters & setters /////////
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
}
我的JSON请求对象:
{
"name" : "John",
"userId" : "ff06c5a4-135c-40b7-83f3-3648ec035efc"
}
我正在使用具有以下依赖关系的标准Jersey原型(版本2.23.2):
<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>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.50</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
答案 0 :(得分:1)
AFAIK 您可以使用自定义XmlAdapter
修复它:
public class UUIDAdapter extends XmlAdapter<String, UUID> {
@Override
public UUID unmarshal(String v) throws Exception {
return UUID.fromString(v);
}
@Override
public String marshal(UUID v) throws Exception {
return v.toString();
}
}
然后使用@XmlJavaTypeAdapter
注释
@XmlRootElement
public class DriverJson {
@XmlJavaTypeAdapter(UUIDAdapter.class)
private UUID id;
@XmlJavaTypeAdapter(UUIDAdapter.class)
private UUID userId;
/* ... */
}