1

I have a JSON Object with the following structure:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Record {
private String tid;
private String eid;

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime ts;

public Record() {
}
}

When I try and convert this to a string using the following method,

public static String convertToJSON(Object object) {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json;
        try {
            json = ow.writeValueAsString(object);
            LOGGER.info("(convertToJSON) JSON: {}", json);
        } catch (Exception e) {
            throw new JSONException("Error Converting JSON To string", e);
        }
        return json;
    }

I get a comma separated value as below: "ts" : [ 2021, 4, 4, 20, 17, 50, 522000000 ]

I want this printed as ISO-UTC "ts" : "2021-04-04 20:46:44:932" or "ts" : "2021-04-04 20:46:44:932z".

One was would be to add @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss:SSS") to the record object but I would not prefer not changing the Json object definition as this has inflight data impact in production. Is there a way to change my convertToJSON method to achieve this.

Sameer
  • 757
  • 1
  • 14
  • 35
  • 1
    Possible duplicate of [Java 8 LocalDate Jackson format](https://stackoverflow.com/questions/28802544/java-8-localdate-jackson-format) – Ahmed HENTETI Apr 04 '21 at 15:54

1 Answers1

2

There are a lot of Stackoverlfow posts about that. It's quite simple, please try :

public class MyTest {
    @Data
    public static class Foo {
        private LocalDateTime date;
    }

    public static void main(String[] args) throws JsonProcessingException {
        Foo foo = new Foo();
        foo.setDate(LocalDateTime.now());
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        System.out.println(objectMapper.writeValueAsString(foo));
    }
}

The result will be : {"date":"2021-04-05T11:19:38.999185"}. Notice that i used @Data from Lombok to simplify. For JavaTimeModule you will probably need to add Maven dependency :

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.12.2</version>
</dependency>
zpavel
  • 951
  • 5
  • 11