jackson-modules-java8
jackson-modules-java8 copied to clipboard
The serialization of an object of type LocalDate did not record its type
Why does the LocalDate type object not record its type after serialization, resulting in the principle type cannot be restored after deserialization, while the date type can。
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper om = new ObjectMapper();
om.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
om.findAndRegisterModules();
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
String json = om.writeValueAsString(new Date());
System.out.println(json);
Object objDeserialized = om.readValue(json,Object.class);
System.out.println(objDeserialized.getClass());
System.out.println("======================");
String json2 = om.writeValueAsString(LocalDate.now());
System.out.println(json2);
Object objDeserialized2 = om.readValue(json2,Object.class);
System.out.println(objDeserialized2.getClass());
}
["java.util.Date","2024-05-11T14:31:56.371+00:00"]
class java.util.Date
======================
"2024-05-11"
class java.lang.String
Is LocalDate declared as final? You are using:
ObjectMapper.DefaultTyping.NON_FINAL
so type id would not be included for final classes.
Note: another, safer way to force use of type id is to apply @JsonTypeInfo on wrapper Bean like:
public class DateValueWrapper {
@JsonTypeInfo(....)
public Object data;
// and getters, setters, if you want
}
because in that case Type Id inclusion will be forced for date field.
Not a bug (although Default Typing usage itself can be confusing -- also, not specific to LocalDate per se). Closing.