我有一个项目需要严格的 json 策略。
例子:
public class Foo {
private boolean test;
... setters/getters ...
}
以下 json 应该可以工作:
{
test: true
}
下面应该失败(抛出异常):
{
test: 1
}
同样适用于:
{
test: "1"
}
基本上,如果有人提供不同于 true
或 false
的内容,我希望反序列化失败。不幸的是,jackson 将 1
视为 true,将 0
视为 false
。我找不到禁用该奇怪行为的反序列化功能。
最佳答案
可以禁用 MapperFeature.ALLOW_COERCION_OF_SCALARS
来自 docs
Feature that determines whether coercions from secondary representations are allowed for simple non-textual scalar types: numbers and booleans.
如果您还希望它适用于null
,请启用DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES
( More Info )
ObjectMapper mapper = new ObjectMapper();
//prevent any type as boolean
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
// prevent null as false
// mapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
System.out.println(mapper.readValue("{\"test\": true}", Foo.class));
System.out.println(mapper.readValue( "{\"test\": 1}", Foo.class));
结果:
Foo{test=true}
Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
coerce Number (1) for type `boolean` (enable
`MapperFeature.ALLOW_COERCION_OF_SCALARS` to allow) at [Source:
(String)"{"test": 1}"; line: 1, column: 10] (through reference chain:
Main2$Foo["test"])
关于java - 如何在 jackson 2.9.x 中禁用 0/1 到 true/false 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372516/