【问题标题】:How do I use a UUID in a @MultipartForm Pojo?如何在 @MultipartForm Pojo 中使用 UUID?
【发布时间】:2021-12-17 04:47:36
【问题描述】:

我想将 我的 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 吗?

【问题讨论】:

标签: rest multipartform-data resteasy quarkus


【解决方案1】:

您需要提供知道如何读取数据的MessageBodyReader&lt;UUID&gt;。类似于以下内容:

@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() 方法,因此没有默认的读取类型的方法。

【讨论】:

  • 谢谢,我会试试的。但是我必须在 @PartType 中指定什么 MediaType ?
  • 它是@PartType(MediaType.APPLICATION_OCTET_STREAM)。谢谢。
猜你喜欢
  • 2012-09-14
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 2021-04-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多