JSON:JsonMappingException尝试反序列化具有空值的对象 [英] JSON: JsonMappingException while try to deserialize object with null values

查看:2042
本文介绍了JSON:JsonMappingException尝试反序列化具有空值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试反序列化包含null-properties的对象并且具有 JsonMappingException

I try to deserialize object that contains null-properties and have the JsonMappingException.

什么我这样做:

String actual = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51," +
                "    \"firstName\" : null}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //EXCEPTION!

但是:如果要扔掉firstName = null属性 - 一切正常!
我的意思是传递下一个字符串:

BUT: if to throw away "firstName = null" property - all works fine! I mean pass the next string:

String test = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //ALL WORKS FINE!

问题
如何避免此例外或承诺杰克逊在序列化期间忽略空值?

Question: How to avoid this exception or to pledge Jackson ignore null-values during serialization?

抛出:

消息:

Message:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: person.Create["person"]->Person["firstName"])

原因:

cause:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: prson.Create["person"]->Person["firstName"])

原因: java.lang.NullPointerException

推荐答案

如果您不想序列化 null 值,则可以使用以下设置(在序列化期间):

If you don't want to serialize null values, you can use the following setting (during serialization):

objectMapper.setSerializationInclusion(Include.NON_NULL);

希望这可以解决您的问题。

Hope this solves your problem.

但是反序列化期间得到的 NullPointerException 对我来说似乎很可疑(杰克逊理想情况下应该能够处理序列化中的 null 值输出)。你能发贴对应 PersonResponse 类的代码吗?

But the NullPointerException you get during deserialization seems suspicious to me (Jackson should ideally be able to handle null values in the serialized output). Could you post the code corresponding to the PersonResponse class?

这篇关于JSON:JsonMappingException尝试反序列化具有空值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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