我有一个需要严格的json策略的项目。
示例:
public class Foo {
private boolean test;
... setters/getters ...
}
以下json应该可以工作:
{
test: true
}
以下应该失败(抛出异常):
{
test: 1
}
同样的:
{
test: "1"
}
基本上,如果某人提供的内容与true
或false
不同,我希望反序列化失败。不幸的是,杰克逊认为1
为真,0
为false
。我找不到禁用这种奇怪行为的反序列化功能。
答案 0 :(得分:2)
可以停用MapperFeature.ALLOW_COERCION_OF_SCALARS
来自docs
确定是否来自次要的强制的功能 允许表示简单的非文本标量类型: 数字和布尔值。
如果您还希望它适用于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"])