目前,当输入 json 对象作为 POST 请求正文时,Jersey 将忽略任何它无法识别的键/值对。
示例:
public class TestObject{
private String value1;
private Integer value2;
// appropriate getters and setters
}
JSON 对象:
{
"value1":"test",
"value2":1,
"value3":"wrong"
}
在上述情况下,Jersey 将接受两个预期值并创建 TestObject,忽略“value3”输入。
如果 JSON 对象中的任何内容无法识别,是否有办法强制 Jersey 抛出异常而不是忽略该值?
编辑:
我的 Controller 看起来像这样:
@POST
@Consumes("application/json")
public Response handleTestObject(TestObject testObject){
//method execution here
}
所以我依靠 Jersey 将 json 输入转换为 TestObject
最佳答案
当你使用jackson进行转换时,如果传递未知参数,它实际上应该默认抛出异常。我已经用 Jackson 2.26 尝试过:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.26</version>
</dependency>
并且在没有任何进一步配置的情况下抛出了以下异常:
Unrecognized field "value3" (class de.jan.model.TestObject), not marked as ignorable (one known property: "test"])
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@2ff055a5; line: 1, column: 25] (through reference chain: de.jan.model.TestObject["value3"])%
因此,如果您不受其他任何限制,您可以切换到 Jackson 进行转换。
如果您已经在使用 jackson 但仍然没有收到此异常,则您(或您正在使用的某些库)可能已在某处禁用了此行为。要恢复它,您可以将以下注释添加到您的类 TestObject
中:
@JsonIgnoreProperties(ignoreUnknown = false)
这将导致 Jackson 在反序列化该特定类的实例时抛出其他字段的异常。
要为所有对象配置此行为,您需要创建一个自定义 ObjectMapper
解析器,如下所示:
@Provider
@Produces("application/json")
public class ObjectMapperResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperResolver() {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
并在您的ResourceConfig
中注册此类。
如果您使用 gson,您可能无能为力。支持未知属性处理程序存在一个 Unresolved 问题,但到目前为止尚未发布。您可以在其 issue tracker 中找到有关此内容的更多信息,包括用于手动检查其他字段的代码片段。
关于java - Jersey 忽略 POST 请求正文中无法识别的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547418/