可以禁用MapperFeature.ALLOW_COERCION_OF_SCALARS
来自文档
确定对于简单的非文本标量类型是否允许来自辅助表示的强制的功能:数字和布尔值。
如果您还希望它适用null
,请启用DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES
(更多信息)
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"])