rest - 如何在 @MultipartForm Pojo 中使用 UUID?
问题描述
我想将我的 DTO 中的 UUID转移到我的资源方法中。
我的方法:
@POST
@Path(("/upload"))
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response sendMultipartData(@MultipartForm MultipartBodyRequestDto data) {
// Do stuff [...]
return Response.ok().entity(responseDto).build();
}
我的 DTO:
public class MultipartBodyRequestDto {
// Other properties [...]
@NotNull
@FormParam("file")
@PartType(MediaType.APPLICATION_OCTET_STREAM)
public InputStream file;
@NotNull
@FormParam("id")
@PartType(MediaType.TEXT_PLAIN) // <-- What do I have to select here ?
public UUID id;
}
我收到此错误:
“RESTEASY007545:找不到媒体类型的 MessageBodyReader:text/plain;charset=UTF-8 和类类型 java.util.UUID”
切换到 String 和 @PartType(MediaType.TEXT_PLAIN) 时,它可以工作,但我必须自己转换 id。
Resteasy 应该能够转换它,毕竟我在其他端点中使用 UUID,如下所示:
@GET
@Path("/{id}")
public Response get(@PathParam("id") @NotNull UUID id) {
// Do stuff [...]
}
我是否必须实现特定的MessageBodyReader?
解决方案
您需要提供一个MessageBodyReader<UUID>
知道如何读取数据的。类似于以下内容:
@Provider
public class UuidMessageBodyReader implements MessageBodyReader<UUID> {
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
return type.isAssignableFrom(UUID.class);
}
@Override
public UUID readFrom(final Class<UUID> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
final byte[] buffer = new byte[256];
int len;
while ((len = entityStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
return UUID.fromString(out.toString(resolve(mediaType)));
} finally {
entityStream.close();
}
}
private String resolve(final MediaType mediaType) {
if (mediaType != null) {
final String charset = mediaType.getParameters().get("charset");
if (charset != null) {
return charset;
}
}
return "UTF-8";
}
}
请注意,这只是一个简单的示例,可能有更有效的方法来执行此操作。
它在您的另一个端点上工作的原因是它只会返回UUID.toString()
. 但是,没有读取类型的默认方法,因为没有UUID.valueOf()
方法。
推荐阅读
- postgresql - 如何使 PostgreSQL 约束仅适用于新值
- php - ngrok 在 laravel 6 中返回 419 并禁用 CSRF 令牌
- r - 在 R 中导入多张工作簿的几张
- python - 是什么导致熊猫和 geopandas 出现此列表索引超出范围错误?
- tensorflow - 特征嵌入应该在神经网络中的 dropout 层之前还是之后进行?
- angular - 用户类型 3-4 字符的 Mat-Select Angular 选项过滤器
- sql - 创建临时表,它复制一列的值但更改另一列的值
- regex - 即使之前有空格,如何匹配数字?
- microsoft-teams - 共享屏幕菜单中的按钮未显示在 Microsoft 团队中
- google-sheets - 谷歌表格解析 json