我尝试将对象可序列化为json字符串,这将有一个空字段。当所有字段初始化时-都工作良好,但是当我设置为字段null
值时,出现了异常:
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException).
我的代码:
public String toJsonString(T t) throws JsonProcessingException{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
String dtoAsString = objectMapper.writeValueAsString(t); //string where I got the exception
return dtoAsString;
}
目的:
SomeObject{
@JsonSerialize(using = LocalDateSerializer.class)
LocalDate date = LocalDate.now();
Long value = null;
}
PS:
问题是我无法someObject
自动解析json中的内容,因为遇到了另一个异常-我需要解析date
为特殊的字符串格式。因此,我需要完全按照自己的方式使用-objectMapper(Gson()。toString对我的LocalDate
值进行序列化有误)。
我找到了解决方案:
由于字段之一尚未初始化,因此发生错误,因此ObjectMapper
引发异常。
只需添加@JsonInclude(JsonInclude.Include.NON_NULL)
到您的POJO类:
@JsonInclude(JsonInclude.Include.NON_NULL)
SomeObject{
String date = "11.01.19";
Long value = null;
}
结果我们将得到没有空字段的json:
{
"date" : "11.09.19"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句