如何告诉杰克逊将"null"反序列化字符串为空文字? [英] How to tell Jackson to deserialize "null" string to null literal?

查看:144
本文介绍了如何告诉杰克逊将"null"反序列化字符串为空文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web服务,该服务将"null"作为任何属性的字符串而不是null文字输出.它几乎针对所有数据类型(字符串或日期)执行此操作.例如,在理想情况下,它会返回

I have a webservice which prints "null" as a string for any property instead of null literal. It does that for almost all data types(String or Date). For example, in ideal case it returns

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

但有时它会返回:

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

将title属性值设置为"null",而不是将其设置为null. 或某个时候:

Which makes the title property value as "null" instead of setting it to null. Or sometime this:

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

这使得反序列化失败,因为dateformat不匹配. 在反序列化期间,如何配置objectmapper或注释模型类以解决这些问题?

Which makes the deserialization fail because the dateformat does not match. How can I configure objectmapper or annotate my model classes to resolve these problems during deserialization?

我的模型类如下:

@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服务.预先感谢

It's an android app so I have no control over the webservice. Thanks in advance

推荐答案

由于

Since someone asked this question again a few minutes ago, I did some research and think I found a good solution to this problem (when dealing with Strings).

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

You have to create a custom JsonDeserializer class as follows:

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的方式和位置,但是看起来像这样:

Last but not least, all you have to do is tell your ObjectMapper that it should use your custom json string deserializer. This depends on how and where you use your ObjectMapper but could look like that:

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

这篇关于如何告诉杰克逊将"null"反序列化字符串为空文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆