I try to serializable object to json String, what would have a null fields.
When all fields initialize - all works well, but when I set to field null
value, I got the exception:
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException).
My code:
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;
}
Object:
SomeObject{
@JsonSerialize(using = LocalDateSerializer.class)
LocalDate date = LocalDate.now();
Long value = null;
}
PS:
Problem in that what I cannot parse someObject
automatically in json, since I got the another exception - I need parse date
into special string format. So I need use exactly my way - objectMapper (Gson().toString has wrong serialized my LocalDate
value).
I am found the resolving:
Error was occurred since one of the fields has been not initialized, so ObjectMapper
trowed exception.
Just add @JsonInclude(JsonInclude.Include.NON_NULL)
to you POJO class:
@JsonInclude(JsonInclude.Include.NON_NULL)
SomeObject{
String date = "11.01.19";
Long value = null;
}
in result we will be get json without nullable field:
{
"date" : "11.09.19"
}