我需要手动构造一个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正常工作。
我可以以适当的方式找到解决方案,但是我的工作看起来像这样:该代码在实际的服务实现中。
@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();
}
}
问候