可以禁止docs
功能,確定從次級 表示強制轉換是否允許進行簡單的非文本標量類型MapperFeature.ALLOW_COERCION_OF_SCALARS
: 數字和布爾值。
如果你還希望它爲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"])
謝謝,這是我需要的。 –