【发布时间】:2019-10-31 18:28:11
【问题描述】:
我尝试将对象序列化为 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:
问题在于我无法在 json 中自动解析 someObject,因为我遇到了另一个异常 - 我需要将 date 解析为特殊的字符串格式。所以我需要完全按照我的方式使用 - objectMapper(Gson().toString 错误地序列化了我的 LocalDate 值)。
【问题讨论】:
标签: java json serialization objectmapper