NullableStringSerializer

object NullableStringSerializer : KSerializer<String?>

A custom serializer for handling nullable strings in a standardized way.

This serializer ensures that blank strings (e.g., "") are deserialized as null. It provides a convenient mechanism to handle string fields that may either be blank or null in the input data.

Example Usage:

@Serializable
data class Example(
    @Serializable(with = NullableStringSerializer::class)
    val description: String?
)

val json = """{"description": ""}"""
val result = Json.decodeFromString<Example>(json)
println(result.description) // Output: null

val serialized = Json.encodeToString(Example(description = null))
println(serialized) // Output: {"description":null}

Properties

Link copied to clipboard
open override val descriptor: SerialDescriptor

The serial descriptor for a nullable string.

Functions

Link copied to clipboard
open override fun deserialize(decoder: Decoder): String?

Deserializes a string value, converting blank strings to null.

Link copied to clipboard
open override fun serialize(encoder: Encoder, value: String?)

Serializes a nullable string.