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 .
Asked
Active
Viewed 133 times
2
-
The format with the colon is the [ISO 8601 standard](https://en.wikipedia.org/wiki/ISO_8601). You can’t persuade the consumer of your JSON to accept that? – Ole V.V. Jan 28 '23 at 12:49
-
`ZoneId` is harder. It represents an ID of a time zone that in virtually all cases has had and will have different UTC offset through history and future. I don’t see any reasoable way to serialize that to a numeric string, and under no circumstances will the receiver be able to reconstruct the `ZoneId` object at the other end. – Ole V.V. Jan 28 '23 at 12:55
-
And no, I believe there is no support for `+03.00` with a point/dot neither in Jackson nor in java.time. If we can’t get rid of that requirement, I would use a custom serializer and inside that something like `ZoneOffset.ofHours(3).toString().replace(':', '.')` (this gives `+03.00`). – Ole V.V. Jan 28 '23 at 12:58
-
Thank you, I resolved this task by custom serializer with replacing ':' by '.' – trom Jan 29 '23 at 17:02
2 Answers
2
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.

Arvind Kumar Avinash
- 71,965
- 6
- 74
- 110
2
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

trom
- 61
- 5