Skip to content

Commit 5efb20f

Browse files
committed
Check shouldEncodeElementDefault in InstantComponentSerializer
1 parent 7587980 commit 5efb20f

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

core/commonMain/src/kotlinx/serialization/builtins/InstantComponentSerializer.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public object InstantComponentSerializer : KSerializer<Instant> {
5252
override fun serialize(encoder: Encoder, value: Instant) {
5353
encoder.encodeStructure(descriptor) {
5454
encodeLongElement(descriptor, 0, value.epochSeconds)
55-
if (value.nanosecondsOfSecond != 0) {
55+
if (value.nanosecondsOfSecond != 0 || shouldEncodeElementDefault(descriptor, 1)) {
5656
encodeIntElement(descriptor, 1, value.nanosecondsOfSecond)
5757
}
5858
}

formats/json-tests/commonTest/src/kotlinx/serialization/InstantSerializationTest.kt

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,21 @@ class InstantSerializationTest: JsonTestBase() {
4545
Pair(Instant.fromEpochSeconds(987654321, 123456789),
4646
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":123456789}"),
4747
Pair(Instant.fromEpochSeconds(987654321, 0),
48-
"{\"epochSeconds\":987654321}"),
48+
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":0}"),
4949
)) {
5050
assertJsonFormAndRestored(serializer, instant, json)
5151
}
52-
// check that having a `"nanosecondsOfSecond": 0` field doesn't break deserialization
52+
// by default, `nanosecondsOfSecond` is optional
53+
assertJsonFormAndRestored(serializer, Instant.fromEpochSeconds(987654321, 0),
54+
"{\"epochSeconds\":987654321}", Json { })
55+
// having a `"nanosecondsOfSecond": 0` field doesn't break deserialization
5356
assertEquals(Instant.fromEpochSeconds(987654321, 0),
5457
Json.decodeFromString(serializer,
5558
"{\"epochSeconds\":987654321,\"nanosecondsOfSecond\":0}"))
59+
// as does not having a `"nanosecondsOfSecond"` field if `encodeDefaults` is true
60+
assertEquals(Instant.fromEpochSeconds(987654321, 0),
61+
default.decodeFromString(serializer,
62+
"{\"epochSeconds\":987654321}"))
5663
// "epochSeconds" should always be present
5764
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{}") }
5865
assertFailsWith<SerializationException> { Json.decodeFromString(serializer, "{\"nanosecondsOfSecond\":3}") }

0 commit comments

Comments
 (0)