gpt4 book ai didi

java - 如何告诉 jackson 将 "null"字符串反序列化为空文字?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:21 24 4
gpt4 key购买 nike

我有一个 web 服务,它将“null”打印为任何属性的字符串,而不是 null 文字。它对几乎所有数据类型(字符串或日期)都这样做。例如,在理想情况下它返回

{
"item" : {
"title": "Some title",
"expires": "2014-11-02 00:00:00"
}
}

但有时它返回:

{
"item" : {
"title": "null",
"expires": "2014-11-02 00:00:00"
}
}

这使得 title 属性值为“null”而不是将其设置为 null。或者有时这样:

{
"item" : {
"title": "Some title",
"expires": "null"
}
}

这使得反序列化失败,因为日期格式不匹配。如何配置 objectmapper 或注释我的模型类以解决反序列化期间的这些问题?

我的模型类如下所示:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Item {
public String title;
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
public Date expires;
}

这是一个 Android 应用程序,所以我无法控制 Web 服务。提前致谢

最佳答案

someone asked this question again几分钟前,我做了一些研究,认为我找到了解决这个问题的好方法(在处理字符串时)。

您必须创建一个自定义的 JsonDeserializer 类,如下所示:

class NullStringJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String result = StringDeserializer.instance.deserialize(p, ctxt);
return result!=null && result.toLowerCase().equals(null+"") ? null : result;
}
}

最后但同样重要的是,您所要做的就是告诉您的 ObjectMapper 它应该使用您的自定义 json 字符串反序列化器。这取决于您使用 ObjectMapper 的方式和位置,但可能看起来像这样:

ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new NullStringJsonDeserializer());
objectMapper.registerModule(module);

关于java - 如何告诉 jackson 将 "null"字符串反序列化为空文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881024/

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