我想反序列化我在 JSON 中获得的一些 boolean 值。问题是这些值可以是 null、true、false、“true”、false、“Y”或“N”。
我已经创建了自己的 boolean 反序列化器
public class CustomBooleanDeserializer extends JsonDeserializer<Boolean> {
final protected Class<?> _valueClass = Boolean.class;
@Override
public Boolean deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
return _parseBooleanPrimitive2(jp, ctxt);
}
protected final boolean _parseBooleanPrimitive2(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
LogUtils.d("PARSE BOOLEAN");
JsonToken t = jp.getCurrentToken();
if (t == JsonToken.VALUE_TRUE) {
return true;
}
if (t == JsonToken.VALUE_FALSE) {
return false;
}
if (t == JsonToken.VALUE_NULL) {
return false;
}
if (t == JsonToken.VALUE_NUMBER_INT) {
return (jp.getIntValue() != 0);
}
if (t == JsonToken.VALUE_STRING) {
String text = jp.getText().trim();
if ("true".equals(text)) {
return true;
}
if ("false".equals(text) || text.length() == 0) {
return Boolean.FALSE;
}
if ("N".equalsIgnoreCase(text) || text.length() == 0) {
return Boolean.FALSE;
}
if ("Y".equalsIgnoreCase(text)) {
return Boolean.TRUE;
}
throw ctxt.weirdStringException(_valueClass, "only \"true\" or \"false\" recognized");
}
// Otherwise, no can do:
throw ctxt.mappingException(_valueClass);
}
但是,如果我这样注册,这个反序列化器永远不会被调用:
Version version = new Version(1, 0, 0, "SNAPSHOT");
SimpleModule module = new SimpleModule("MyModuleName", version);
module = module.addDeserializer(new CustomBooleanDeserializer());
objectMapper.registerModule(module);
另一方面,如果我对 boolean 字段使用 @JsonDeserialize(using = CustomBooleanDeserializer.class)
,它会被调用并且效果很好。唯一的问题是,如果属性为 null,我会得到这个异常:
org.codehaus.jackson.map.JsonMappingException: Problem deserializing property 'show_query_cond' (expected type: [simple type, class boolean]; actual type: [NULL]), problem: invalid value for field (through reference chain: com.csf.model.CSTable["show_query_cond"])
因此,如果 boolean 属性为 null,我的反序列化器就没有机会运行。另外,我尝试使用 mapper.configure(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
但如果我使用 @JsonDeserialize 注释,仍然会抛出异常。
有人知道怎么做吗?
最佳答案
至于注册,这可能是由于 Java 同时具有原始 boolean
和 Object wrapper Boolean
。因此,您需要使用 java.lang.Boolean
和 Boolean.TYPE
来注册它——后者是原始类型的占位符类。
Null 处理是不同的问题:不为它们调用反序列化方法。不过还是有方法的
JsonDeserializer.getNullValue()
应该这样称呼;对于基元,您必须返回“Boolean.FALSE”,因为您不能将 null 分配给基元值(返回包装是可以的;它会得到正确处理)。
关于json - jackson 反序列化自定义 boolean json 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9633316/