0

I've been trying to serialize LocalDateTime to a string and deserialize the same String back into a LocalDateTime object.

Using the following code:

public void testSerialization(){

    Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    serializer.setObjectMapper(objectMapper);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String results = "";
    Map<String, Object> resultMap;

    // Object I want to serialize and deserialize

    HashMap<String, Object> map = new HashMap<>();
    LinkedHashMap<String, Object> lMap = new LinkedHashMap<>();
    lMap.put("DATE", LocalDateTime.of(2022,4,12,1,54));
    map.put("reader.start.after", lMap);

    // serialize 

    try{
      serializer.serialize(map, out);
      results = new String(out.toByteArray(), "ISO-8859-1");
    }catch (Exception e){
      System.out.println(e);
    }
}

This serializes the object to:

{"reader.start.after":{"DATE":"2022-04-12T01:54:00"}}

When I attempt to deserialize using:

    Map<String, Object> resultMap;
    try{
      ByteArrayInputStream in = new ByteArrayInputStream(results.getBytes("ISO-8859-1"));
      resultMap = serializer.deserialize(in);
    }catch (Exception e){
      System.out.println(e);
    }

It almost deserializes everything correctly except it doesn't deserialize "2022-04-12T01:54:00" back into a LocalDateTime. Does anyone know how to have it deserialize back into LocalDateTime and not a String?

CKT
  • 383
  • 2
  • 8
  • Have you seen [this](https://stackoverflow.com/a/29959842/8557381)? – Novy Apr 18 '22 at 20:15
  • Is there a reason why you write your own serializer instead of using the default one which does that already? – Tom Apr 18 '22 at 20:16
  • @Tom My code is running in Spring Batch and I started getting errors after upgrading to the Spring Boot 2.6.6. I was getting errors serializing LocalDateTime and a lot of posts on StackOverflow solved their issues with the serialization setup in my post. The only problem is deserializing. – CKT Apr 18 '22 at 20:44

0 Answers0