I am not able to get JsonDeserializer to process null values. I have a json file I am reading from where there are just four values for my record type: Case 1, Case 2, *, or null. JsonDeserializer works fine for the first 3. However, it seems to do nothing when encountering a null. Based on the code (see my custom deserializer below), I would expected the line
text = StringUtils.upperCase(jsonParser.getText());
to either throw an exception (and thus assign text = "NULL). Or, return an empty string as per
if (StringUtils.isBlank(text))
where likewise I assign text = "NULL". However, neither of these ever happens. It seems as though the null is not processed at all (which is not possible, right?). My
System.out.println("TEXT: " + text);
always prints Case 1, Case 2, or *, but never NULL. It literally seems to skip the null entry in the file, or at least does not process it in any way that is accounted for in my code. I would be grateful for any ideas. Thank you!!
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import my.local.CustomValue;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
public class CustomDeserializer extends JsonDeserializer<CustomValue> {
@Override
public CustomValue deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) {
CustomValue retVal = null;
// Get the text from the JSON
String text = null;
try {
text = StringUtils.upperCase(jsonParser.getText());
} catch (IOException e) {
e.printStackTrace();
text = "NULL";
}
System.out.println("TEXT: " + text);
// If the text is empty or null, make it NULL
if (StringUtils.isBlank(text)) {
text = "NULL";
}
// Based on the text value, return the appropriate retVal
switch (text) {
case "Case 1":
retVal = CustomValue.CASE1;
break;
case "Case 2":
retVal = CustomValue.CASE2;
break;
case "NULL":
retVal = CustomValue.NULL;
break;
case "*":
retVal = CustomValue.WILDCARD;
break;
default:
retVal = CustomValue.NULL;
break;
}
return retVal;
}
}