gpt4 book ai didi

java - JsonDeserializer 不处理空值

转载 作者:行者123 更新时间:2023-12-01 16:23:58 24 4
gpt4 key购买 nike

我无法让 JsonDeserializer 处理空值。我正在读取一个 json 文件,其中记录类型只有四个值:Case 1、Case 2、* 或 null。 JsonDeserializer 对于前 3 个工作正常。但是,当遇到 null 时,它似乎什么也不做。根据代码(请参阅下面的自定义反序列化器),我期望该行

text = StringUtils.upperCase(jsonParser.getText());

抛出异常(并因此分配 text = "NULL)。或者,返回一个空字符串

if (StringUtils.isBlank(text))

同样我分配text =“NULL”。然而,这两种情况都没有发生。似乎 null 根本没有被处理(这是不可能的,对吧?)。我的

System.out.println("TEXT: " + text);

始终打印 Case 1、Case 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;
}
}

最佳答案

JsonDeserializer.deserialize 的 JavaDoc声明如下:

"... Note that this method is never called for JSON null literal, and thus deserializers need (and should) not check for it."

Jackson 自行处理 null 值,并且不会调用自定义反序列化器的 deserialize。要自定义为 null 返回的值,您必须重写反序列化器的 getNullValue 方法。

关于java - JsonDeserializer 不处理空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62196103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com