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

Iterate over element indicies in ObjectSerializer in order to let the… #1916

Merged
merged 1 commit into from Apr 27, 2022
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 @@ -40,7 +40,14 @@ internal class ObjectSerializer<T : Any>(serialName: String, private val objectI
}

override fun deserialize(decoder: Decoder): T {
decoder.beginStructure(descriptor).endStructure(descriptor)
decoder.decodeStructure(descriptor) {
when (val index = decodeElementIndex(descriptor)) {
CompositeDecoder.DECODE_DONE -> {
return@decodeStructure
}
else -> throw SerializationException("Unexpected index $index")
}
}
return objectInstance
}
}
Expand Up @@ -5,10 +5,10 @@
package kotlinx.serialization.features

import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonTestBase
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.test.Test
import kotlinx.serialization.test.*
import kotlin.test.*

class ObjectSerializationTest : JsonTestBase() {

Expand Down Expand Up @@ -46,4 +46,17 @@ class ObjectSerializationTest : JsonTestBase() {
json
)
}

@Test
fun testUnknownKeys() {
val string = """{"metadata":"foo"}"""
assertFailsWithMessage<SerializationException>("ignoreUnknownKeys") {
Json.decodeFromString(
ApiResponse.Error.serializer(),
string
)
}
val json = Json { ignoreUnknownKeys = true }
assertEquals(ApiResponse.Error, json.decodeFromString(ApiResponse.Error.serializer(), string))
}
}