Search code examples
javakotlinjacksonmicronaut

How to change the default serialization/deserialization for Java java.time.OffsetDateTime on Micronaut?


I'm using Micronaut v3.8.1. Micronaut is using Jackson for serialization/deserialization, via Gradle dependency management:

implementation("io.micronaut.serde:micronaut-serde-jackson")

The default serialization for the java.time.OffsetDateTime instances is a number that represents the milliseconds since Epoch.

For example, returning instances of a class represented by the next code (Kotlin) from a controller:

import io.micronaut.serde.annotation.Serdeable
import java.time.OffsetDateTime

@Serdeable
class Thing(val created: OffsetDateTime)

...a single instance of Thing will be serialized to something like:

{
"created": 1674594085000
}

I want to change the configuration, to produce the string representation of that date/time, which is:

{
"created": "2023-01-24T21:01:25.191493200Z"
}

How to achieve this?


Solution

  • Add @JsonFormat(pattern=)

    For example:

    @Serdeable
    data class Thing(@field:JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSZ") val created: OffsetDateTime)
    

    UPDATE: Global Setting

    micronaut:
      application:
        name: kotlinSerde
      serde:
        write-dates-as-timestamps: false # 1
    #    date-format: 'yyyy-MM-dd' #2
    
    1. If you want to use default ISO formats instead of timestamps (ex: "2023-01-30T09:22:01.796846-05:00" vs :1675088195756)
    2. If you want to set a specific date format globally.

    Note: the JsonFormat annotation will be used if declared.