Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly skip unknown keys for objects and structures with zero prope… #1720

Merged
merged 2 commits into from Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -7,6 +7,7 @@ package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
Expand Down Expand Up @@ -56,9 +57,21 @@ internal open class StreamingJsonDecoder(
}

override fun endStructure(descriptor: SerialDescriptor) {
// If we're ignoring unknown keys, we have to skip all undecoded elements,
// e.g. for object serialization. It can be the case when the descriptor does
// not have any elements and decodeElementIndex is not invoked at all
if (json.configuration.ignoreUnknownKeys && descriptor.elementsCount == 0) {
skipLeftoverElements(descriptor)
}
lexer.consumeNextToken(mode.end)
}

private fun skipLeftoverElements(descriptor: SerialDescriptor) {
while (decodeElementIndex(descriptor) != DECODE_DONE) {
// Skip elements
}
}

override fun decodeNotNullMark(): Boolean {
return !(elementMarker?.isUnmarkedNull ?: false) && lexer.tryConsumeNotNull()
}
Expand Down
Expand Up @@ -110,4 +110,21 @@ class JsonModesTest : JsonTestBase() {

@Serializable
data class Box(val double: Double, val float: Float)


@Serializable
object Object

@Serializable
data class Holder(val o: Object)

@Test
fun testIgnoreUnknownKeysObject() = parametrizedTest { jsonTestingMode ->
noLegacyJs {
assertEquals(Holder(Object), lenient.decodeFromString("""{"o":{}}""", jsonTestingMode))
assertEquals(Holder(Object), lenient.decodeFromString("""{"o":{"unknown":{"b":"c"}}}""", jsonTestingMode))
assertEquals(Object, lenient.decodeFromString("""{}""", jsonTestingMode))
assertEquals(Object, lenient.decodeFromString("""{"o":{"unknown":{"b":"c"}}}""", jsonTestingMode))
}
}
}