FasterXML / jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Apache License 2.0
398 stars 116 forks source link

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

Closed penweizgx closed 2 weeks ago

penweizgx commented 3 months ago

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
cowtowncoder commented 3 months ago

Is LocalDate declared as final? You are using:

ObjectMapper.DefaultTyping.NON_FINAL

so type id would not be included for final classes.

cowtowncoder commented 3 months ago

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 commented 2 weeks ago

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