首页 > 解决方案 > Jersey FormDataBodyPart getValueAs 导致“实体实例不包含未转换的内容”。

问题描述

我需要手动构造一个 FormDataBodyPart 对象,然后不久之后我需要使用 getValueAs 将其转换为另一个对象。像这样:

早期的:

FormDataBodyPart fdbp= new FormDataBodyPart("{\"category\":\"Stormware\"}", MediaType.APPLICATION_JSON_TYPE); 
fdbp.setName("theName");

之后:

Attachment metaData = fdbp.getValueAs(Attachment.class);

点击后面的代码行会出现以下错误:

java.lang.IllegalStateException: Entity instance does not contain the unconverted content.
at org.glassfish.jersey.media.multipart.BodyPart.getEntityAs(BodyPart.java:291)
at org.glassfish.jersey.media.multipart.FormDataBodyPart.getValueAs(FormDataBodyPart.java:315)

我不确定如何创建 FormDataBodyPart 对象以使 getValueAs 正常工作。

标签: javarestjerseyjersey-client

解决方案


我可以以适当的方式找到解决方案,但我的解决方法如下所示:此代码在实际服务实现中。

@SuppressWarnings("unchecked")
private <T> T getEntityAs(BodyPart bodyPart, Class<T> clazz) {
        try {
            // used for runtime
            return bodyPart.getEntityAs(clazz);
        } catch (IllegalStateException e) {
            // used for tests
            return (T) bodyPart.getEntity();
        }
}

问候。


推荐阅读