杰克逊:是否有一种方法可以忽略布尔反序列化中的0/1? [英] Jackson: Is there a way to ignore 0/1 on Boolean deserialization?
问题描述
我有一个JSON
对象,该对象具有Boolean
属性,在反序列化期间只需要允许true
或false
.
I have a JSON
object with a Boolean
property that needs to allow only true
or false
during the deserialization.
任何与true
和false
不同的值都将引发异常.
Any value different of true
and false
should throw an exception.
我该怎么做?
例如:
有效的json:
{
"id":1,
"isValid":true
}
无效的json:
{
"id":1,
"isValid":1
}
更新
我尝试了@MichałZiober的建议,效果很好.
Update
I tried what @Michał Ziober proposed and it worked fine.
当我使用Webflux实现Spring应用程序时,我只需要以不同的方式进行配置.我在这里发布了我所做的事情:
As I'm implementing a Spring application (with Webflux) I just had to configure in a different way. I'm posting here what I did:
- 创建从
DelegatingWebFluxConfiguration
扩展的Configuration类
- 覆盖
configureHttpMessageCodecs
方法,在ObjectMapper
上设置属性
- Create a Configuration class extending from
DelegatingWebFluxConfiguration
- Override the
configureHttpMessageCodecs
method setting the property onObjectMapper
@Configuration
public class JacksonConfig extends DelegatingWebFluxConfiguration {
@Override
protected void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
configurer.defaultCodecs()
.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper));
}
}
推荐答案
您需要禁用上面的代码显示:
线程主"中的异常
com.fasterxml.jackson.databind.exc.MismatchedInputException
:无法 类型java.lang.Boolean
的强制数字(1)(启用MapperFeature.ALLOW_COERCION_OF_SCALARS
允许)位于[来源: (文件);行:3,列:14](通过参考链: Pojo ["isValid"])在 com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
Exception in thread "main"
com.fasterxml.jackson.databind.exc.MismatchedInputException
: Cannot coerce Number (1) for typejava.lang.Boolean
(enableMapperFeature.ALLOW_COERCION_OF_SCALARS
to allow) at [Source: (File); line: 3, column: 14] (through reference chain: Pojo["isValid"]) at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
这篇关于杰克逊:是否有一种方法可以忽略布尔反序列化中的0/1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!