Jackson Deserialize custom boolean json property -
i want deserialize boolean values in json. problem values can null, true, false, "true", false, "y" or "n".
i've created 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, deserializer never called if register this:
version version = new version(1, 0, 0, "snapshot"); simplemodule module = new simplemodule("mymodulename", version); module = module.adddeserializer(new custombooleandeserializer()); objectmapper.registermodule(module);
if, on other hand, use @jsondeserialize(using = custombooleandeserializer.class)
boolean fields, called , works great. problem if property null, exception:
org.codehaus.jackson.map.jsonmappingexception: problem deserializing property 'show_query_cond' (expected type: [simple type, class boolean]; actual type: [null]), problem: invalid value field (through reference chain: com.csf.model.cstable["show_query_cond"])
so, if boolean property null, deserializer doesn't chance run. also, tried using mapper.configure(deserializationconfig.feature.fail_on_null_for_primitives, false);
exception still thrown if use @jsondeserialize annotation.
does know how make work?
as registration, due java having both primitive boolean
, object wrapper boolean
. need registed using both java.lang.boolean
, boolean.type
-- latter placeholder class primitive type.
null handling different issue: deserialization method not called them. however, there method
jsondeserializer.getnullvalue()
that should called; , primitives must return 'boolean.false', since can not assign null primitive value (it ok return wrapped; gets handled).
Comments
Post a Comment