Jackson反序列化自定义布尔json属性

Cat*_*san 2 json boolean jackson

我想反序列化一些JSON中的布尔值.问题是这些值可以是null,true,false,"true",false,"Y"或"N".

我已经创建了自己的布尔反序列化器

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);
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我将其注册为以下内容,则永远不会调用此反序列化程序:

Version version = new Version(1, 0, 0, "SNAPSHOT");
SimpleModule module = new SimpleModule("MyModuleName", version);
module = module.addDeserializer(new CustomBooleanDeserializer());
objectMapper.registerModule(module);
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我@JsonDeserialize(using = CustomBooleanDeserializer.class)用于布尔字段,它会被调用并且效果很好.唯一的问题是如果属性为null,我会得到以下异常:

org.codehaus.jackson.map.JsonMappingException:问题反序列化属性'show_query_cond'(期望类型:[simple type,class boolean];实际类型:[NULL]),问题:字段值无效(通过引用链:com.csf .model.CSTable [ "show_query_cond"])

因此,如果boolean属性为null,则我的反序列化器无法运行.此外,我尝试使用mapper.configure(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false);但如果我使用@JsonDeserialize注释仍然抛出异常.

有谁知道如何使这项工作?

Sta*_*Man 7

至于注册,这可能是由于Java同时具有原始boolean包装和对象包装Boolean.所以,你需要同时使用到临时用户它java.lang.BooleanBoolean.TYPE-后者是原始类型的占位符类.

空处理是另一个问题:不会为它们调用反序列化方法.但是,有方法

JsonDeserializer.getNullValue()
Run Code Online (Sandbox Code Playgroud)

应该被称为; 而对于原语,你必须返回'Boolean.FALSE',因为你不能将null赋给原始值(可以返回包装;它得到妥善处理).