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

Added support for null values for nullable enums in lanient mode #2176

Merged
merged 3 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package kotlinx.serialization.json

import kotlinx.serialization.*
import kotlinx.serialization.json.internal.*
import kotlinx.serialization.test.assertFailsWithSerial
import kotlin.test.*

Expand All @@ -25,6 +24,11 @@ class JsonCoerceInputValuesTest : JsonTestBase() {
val foo: String
)

@Serializable
data class NullableEnumHolder(
val enum: SampleEnum?
)

val json = Json {
coerceInputValues = true
isLenient = true
Expand Down Expand Up @@ -99,4 +103,13 @@ class JsonCoerceInputValuesTest : JsonTestBase() {
assertEquals(expected, json.decodeFromString(MultipleValues.serializer(), input), "Failed on input: $input")
}
}

@Test
fun testNullSupportForEnums() = parametrizedTest(json) {
var decoded = decodeFromString<NullableEnumHolder>("""{"enum": null}""")
assertNull(decoded.enum)

decoded = decodeFromString<NullableEnumHolder>("""{"enum": OptionA}""")
assertEquals(SampleEnum.OptionA, decoded.enum)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,16 @@ internal fun SerialDescriptor.getJsonNameIndexOrThrow(json: Json, name: String,
internal inline fun Json.tryCoerceValue(
elementDescriptor: SerialDescriptor,
peekNull: () -> Boolean,
tryPeekNull: () -> Boolean,
shanshin marked this conversation as resolved.
Show resolved Hide resolved
peekString: () -> String?,
onEnumCoercing: () -> Unit = {}
): Boolean {
if (!elementDescriptor.isNullable && peekNull()) return true
if (elementDescriptor.kind == SerialKind.ENUM) {
if (elementDescriptor.isNullable && tryPeekNull()) {
return false
}

val enumValue = peekString()
?: return false // if value is not a string, decodeEnum() will throw correct exception
val enumIndex = elementDescriptor.getJsonNameIndex(this, enumValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ internal open class StreamingJsonDecoder(
private fun coerceInputValue(descriptor: SerialDescriptor, index: Int): Boolean = json.tryCoerceValue(
descriptor.getElementDescriptor(index),
{ !lexer.tryConsumeNotNull() },
{ !lexer.tryConsumeNotNull(false) },
{ lexer.peekString(configuration.isLenient) },
{ lexer.consumeString() /* skip unknown enum string*/ }
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ private open class JsonTreeDecoder(
json.tryCoerceValue(
descriptor.getElementDescriptor(index),
{ currentElement(tag) is JsonNull },
{ currentElement(tag) is JsonNull },
{ (currentElement(tag) as? JsonPrimitive)?.contentOrNull }
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,11 @@ internal abstract class AbstractJsonLexer {
* Tries to consume `null` token from input.
* Returns `true` if the next 4 chars in input are not `null`,
shanshin marked this conversation as resolved.
Show resolved Hide resolved
* `false` otherwise and consumes it.
shanshin marked this conversation as resolved.
Show resolved Hide resolved
*
* If [moveForward] is true and if the next 4 chars in input are `null` then
* current position in lexer move forward on these 4 chars.
*/
fun tryConsumeNotNull(): Boolean {
fun tryConsumeNotNull(moveForward: Boolean = true): Boolean {
shanshin marked this conversation as resolved.
Show resolved Hide resolved
var current = skipWhitespaces()
current = prefetchOrEof(current)
// Cannot consume null due to EOF, maybe something else
Expand All @@ -261,7 +264,10 @@ internal abstract class AbstractJsonLexer {
* distinguish it from 'null'
*/
if (len > 4 && charToTokenClass(source[current + 4]) == TC_OTHER) return true
currentPosition = current + 4

if (moveForward) {
currentPosition = current + 4
}
return false
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ private open class DynamicInput(
json.tryCoerceValue(
descriptor.getElementDescriptor(index),
{ getByTag(tag) == null },
{ getByTag(tag) == null },
{ getByTag(tag) as? String }
)

Expand Down