Jackson反序列化自定义布尔json属性 [英] Jackson Deserialize custom boolean json property

查看:955
本文介绍了Jackson反序列化自定义布尔json属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to deserialize some boolean values that I get in a JSON. The problem is that those values can be null, true, false, "true", false, "Y" or "N".

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

I've created my own boolean deserializer

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);
    }

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

However, this deserializer is never called if I register it as this:

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

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

If, on the other hand, I use @JsonDeserialize(using = CustomBooleanDeserializer.class) for the boolean fields, it does get called and works great. The only problem is that if the property is null, I get this exception:


org.codehaus.jackson.map.JsonMappingException:问题反序列化
属性'show_query_cond'(预期类型:[简单类型,类
布尔];实际类型:[NULL]),问题:字段
的值无效(通过引用链:com.csf .model.CSTable [show_query_cond])

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"])

因此,如果布尔属性为null,我的反序列化器就没有机会跑步。另外,我尝试使用 mapper.configure(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES,false); 但如果我使用@JsonDeserialize注释,仍会抛出异常。

So, if the boolean property is null, my deserializer doesn't get a chance to run. Also, I tried using mapper.configure(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false); but the exception is still thrown if I use the @JsonDeserialize annotation.

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

Does anyone know how to make this work?

推荐答案

关于注册,这是可能是由于Java同时具有原始 boolean 和Object wrapper Boolean 。所以你需要使用 java.lang.Boolean Boolean.TYPE 注册它 - 后者是占位符类原始类型。

As to registration, this is probably due to Java having both primitive boolean and Object wrapper Boolean. So you need to registed it using both java.lang.Boolean and Boolean.TYPE -- latter is the placeholder class for primitive type.

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

Null handling is different issue: deserialization method is not called for them. However, there is method

JsonDeserializer.getNullValue()

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

that should be called; and for primitives you must then just return 'Boolean.FALSE', since you can not assign null to a primitive value (it is ok to return wrapped; it gets properly handled).

这篇关于Jackson反序列化自定义布尔json属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆