how to deserialize a blank json string value to null for java.lang.String -
i trying simple json de-serialize in java object. however, getting empty string values java.lang.string property values. in rest of properties, blank values converting null values(which want).
my json , java class listed below:
json string:
{ "eventid" : 1, "title" : "sample event", "location" : "" } java code:
eventbean class pojo:
public class eventbean { public long eventid; public string title; public string location; } my main class code :
objectmapper mapper = new objectmapper(); mapper.disable(deserializationfeature.fail_on_unknown_properties); mapper.enable(deserializationfeature.accept_empty_string_as_null_object); try { file file = new file(jsontest.class.getclassloader().getresource("event.txt").getfile()); jsonnode root = mapper.readtree(file); // find out applicationid eventbean e = mapper.treetovalue(root, eventbean.class); system.out.println("it is"+ e.location); i expecting print " is null". instead, getting "it is". obviously, jackson not treating blank string values null while converting java.lang.string object type. read somewhere expected. however, want avoid java.lang.string too. there simple way?
jackson give null other objects, string give empty string.
but can use custom jsondeserializer this:
class customdeserializer extends jsondeserializer<string> { @override public string deserialize(jsonparser jsonparser, deserializationcontext context) throws ioexception, jsonprocessingexception { jsonnode node = jsonparser.readvalueastree(); if (node.astext().isempty()) { return null; } return node.tostring(); } } in class have use location field:
class eventbean { public long eventid; public string title; @jsondeserialize(using = customdeserializer.class) public string location; }
Comments
Post a Comment