java - 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 正常工作。
解决方案
我可以以适当的方式找到解决方案,但我的解决方法如下所示:此代码在实际服务实现中。
@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();
}
}
问候。
推荐阅读
- java - 是否可以在 Spring Boot 中全局管理错误?
- typescript - 找不到打字稿声明文件 .d.ts / 不是模块
- r - R按日期分组有问题吗?
- sql - 使用具有多个条件的 Dataform 增量更新 BigQuery 表
- java - CrudRepository 的 deleteById 方法只生成选择查询,不生成删除查询
- javascript - 如何访问 SVG 文本标签内的 tspan?
- python - python中的系列数据框
- php - symfony 从代码中设置本地语言 - php
- javascript - 当我为 server.js 使用以下代码时,服务器将永远加载
- unit-testing - 监视从 React 功能组件调用的函数