我在使用Wildfly 18和Resteasy。
通过在JSON API的主体上传递一个未知属性,我得到了这样的结果。
Unrecognized field "foo" (class xxx), not marked as ignorable(未识别的字段 "foo"(类xxx),未标记为可忽略)
我知道这是一个jackson提供者的问题,在过去的项目中,我用这个提供者解决了。
@Provider
public class JerseyObjectMapperProvider implements ContextResolver<ObjectMapper> {
private ObjectMapper defaultMapper;
public JerseyObjectMapperProvider() {
MapperConfigurator mapperConfig = new MapperConfigurator(null, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
mapperConfig.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
defaultMapper = mapperConfig.getDefaultMapper();
}
@Override
public ObjectMapper getContext(Class<?> type) {
return defaultMapper;
}
}
现在我已经在EE8 JakartaEE上移动了,它包含了框架上的JsonB指令,因此我使用了 JsonbConfig. 这是我的供应商。
@Provider
@Priority(Priorities.ENTITY_CODER)
public class JSONBConfiguration implements ContextResolver<Jsonb> {
private Jsonb jsonb;
public JSONBConfiguration() {
JsonbConfig config = new JsonbConfig()
.withFormatting(true)
.withNullValues(true)
.withPropertyNamingStrategy(PropertyNamingStrategy.IDENTITY)
.withPropertyOrderStrategy(PropertyOrderStrategy.ANY)
.withDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ITALY);
jsonb = JsonbBuilder.create(config);
}
@Override
public Jsonb getContext(Class<?> type) {
return jsonb;
}
}
有什么办法可以设置忽略未知属性与 JsonbConfig 像上面的绘图仪?
你可能在使用 Yasson,JSON-B的参考实现。Yasson有一个选项 FAIL_ON_UNKNOWN_PROPERTIES(未知属性). 这个选项是非标准的,即它不是JSON-B规范的一部分。这个选项是 残疾 默认情况下,因此反序列化应该忽略未知属性,而不是抛出异常。您可以按以下方式配置此属性。
JsonbConfig config = new JsonbConfig().setProperty(org.eclipse.yasson.YassonConfig.FAIL_ON_UNKNOWN_PROPERTIES, true);
Jsonb jsonb = JsonbBuilder.create(config);