我有一个 JSON
对象,它有一个 Boolean
属性,在反序列化。
任何不同于 true
和 false
的值都应该抛出异常。
我该怎么做?
例如:
有效的 json:
{
"id":1,
"isValid":true
}
无效的 json:
{
"id":1,
"isValid":1
}
更新
我尝试了@Michał Ziober 的建议,效果很好。
当我正在实现一个 Spring 应用程序(使用 Webflux)时,我只需要以不同的方式进行配置。我在这里发布我所做的:
- 创建一个扩展自
DelegatingWebFluxConfiguration
的配置类 - 覆盖
configureHttpMessageCodecs
方法设置ObjectMapper
的属性>
@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));
}
}
最佳答案
您需要禁用 ALLOW_COERCION_OF_SCALARS特点:
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
System.out.println(mapper.readValue(jsonFile, Pojo.class));
}
}
class Pojo {
private int id;
private Boolean isValid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Boolean getIsValid() {
return isValid;
}
public void setIsValid(Boolean valid) {
isValid = valid;
}
@Override
public String toString() {
return "Pojo{" +
"id=" + id +
", isValid=" + isValid +
'}';
}
}
以上代码打印:
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)
关于java - Jackson:有没有办法在 boolean 反序列化中忽略 0/1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778322/