ZoneOffset ZoneId custom serialization

237 Views Asked by At

What is the best way to serialize ZoneId or ZoneOffset from format +03:00 to format +03.00 using Jackson? Or may be there is another way how to change : to .

2

There are 2 best solutions below

0
On

The zone offset, +03:00 is already in the ISO 8601 standard format. Therefore, you should educate the publisher/consumer to stick to it. However, if you want to change it in the desired format for any reason, here is how you can do it:

import java.time.ZoneOffset;

class Main {
    public static void main(String[] args) {
        ZoneOffset offset = ZoneOffset.of("+03:00");
        String formatted = offset.toString().replace(':', '.');
        System.out.println(formatted);
    }
}

Output:

+03.00

Learn more about the modern Date-Time API from Trail: Date Time.

0
On

To resolve this tak I made custom serializer:

object ZoneOffsetSerializer : JsonSerializer<ZoneOffset>() {
    override fun serialize(value: ZoneOffset, jsonGenerator: JsonGenerator, serializers: SerializerProvider) {
        val result = "0".takeIf { value.totalSeconds == 0 } ?: value.toString().replace(':', '.')

        jsonGenerator.writeString(result)
    }
}

and used annotation @JsonSerialize(using = ZoneOffsetSerializer::class) for necessary fields