如何在 jackson 2.9.x 中禁用 0/1 到 true/false 的转换

How to disable conversion of 0/1 to true/false in jackson 2.9.x

我有一个项目需要严格的 json 政策。

示例:

public class Foo {
    private boolean test;

    ... setters/getters ...
}

以下 json 应该有效:

{
    test: true
}

下面应该失败(抛出异常):

{
    test: 1
}

同样适用于:

{
    test: "1"
}

基本上,如果有人提供不同于 truefalse 的内容,我希望反序列化失败。不幸的是,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"])