【发布时间】:2020-06-04 13:39:40
【问题描述】:
我无法让 JsonDeserializer 处理空值。我有一个正在读取的 json 文件,其中我的记录类型只有四个值:案例 1、案例 2、* 或 null。 JsonDeserializer 对于前 3 个工作正常。但是,遇到空值时它似乎什么都不做。根据代码(请参阅下面的自定义反序列化器),我预计该行
text = StringUtils.upperCase(jsonParser.getText());
要么抛出异常(并因此分配 text = "NULL)。或者,按照每个返回一个空字符串
if (StringUtils.isBlank(text))
我同样指定 text = "NULL"。然而,这些都没有发生。似乎根本没有处理 null (这是不可能的,对吧?)。我的
System.out.println("TEXT: " + text);
总是打印案例 1、案例 2 或 *,但从不打印 NULL。从字面上看,它似乎跳过了文件中的空条目,或者至少不以我的代码中说明的任何方式处理它。 如有任何想法,我将不胜感激。谢谢!!
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;
}
}
【问题讨论】:
-
输入的 json 文件是有效的 json 吗?在 Json 中,null 表示为未引用的 null,如此处所述 - stackoverflow.com/questions/21120999/representing-null-in-json
-
@Goro,我们使用的格式就像 { "myString": null }