我想將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?
uj5u.com熱心網友回復:
您需要提供一個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()方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/347970.html
