jackson-modules-java8 icon indicating copy to clipboard operation
jackson-modules-java8 copied to clipboard

The serialization of an object of type LocalDate did not record its type

Open penweizgx opened this issue 1 year ago • 2 comments

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

penweizgx avatar May 11 '24 14:05 penweizgx

Is LocalDate declared as final? You are using:

ObjectMapper.DefaultTyping.NON_FINAL

so type id would not be included for final classes.

cowtowncoder avatar May 12 '24 16:05 cowtowncoder

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.

cowtowncoder avatar May 12 '24 16:05 cowtowncoder

Not a bug (although Default Typing usage itself can be confusing -- also, not specific to LocalDate per se). Closing.

cowtowncoder avatar Aug 15 '24 21:08 cowtowncoder