Object serialization
suggest changeSerialization turns an object into bytes or text that can be stored in a file, sent over the network or put in a cache. Deserialization turns it back into an object. In Kotlin you have two main options:
- kotlinx.serialization: the official Kotlin library. A compiler plugin generates the serialization code at compile time, without reflection. It supports JSON, CBOR, ProtoBuf and other formats, and works on JVM, Android, Native and JS.
- java.io.Serializable: the built-in JVM mechanism, used by older Java APIs. It works with Kotlin classes, but it's tied to the JVM and has well-known security problems.
For new code, use kotlinx.serialization. Java libraries such as Jackson (with jackson-module-kotlin) and Gson also work with Kotlin classes, but they rely on reflection and understand Kotlin's default values and null safety less well (Gson not at all).
Setup
kotlinx.serialization needs two things: the compiler plugin, which generates a serializer for every class marked @Serializable, and the runtime library for a format. In Gradle (build.gradle.kts):
plugins {
kotlin("jvm") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21" // same version as Kotlin
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0")
// optional binary formats
implementation("org.jetbrains.kotlinx:kotlinx-serialization-cbor:1.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.11.0")
}
The plugin version must match the Kotlin version. The plugin jar also ships with the command-line compiler, so outside Gradle you can compile with kotlinc -Xplugin=$KOTLIN_HOME/lib/kotlinx-serialization-compiler-plugin.jar -cp <serialization jars> Main.kt. See Gradle configuration for more about build setup.
Encoding and decoding JSON
Mark a class with @Serializable and use Json.encodeToString and Json.decodeFromString:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class User(val id: Int, val name: String, val email: String)
fun main() {
val user = User(1, "Alice", "alice@example.com")
val json = Json.encodeToString(user)
println(json)
val back = Json.decodeFromString<User>(json)
println(back)
println(back == user)
}
{"id":1,"name":"Alice","email":"alice@example.com"}
User(id=1, name=Alice, email=alice@example.com)
true
The type argument of decodeFromString<User> tells the library which serializer to use. Properties of the primary constructor are written in declaration order, with property names as keys.
Default values and nullable properties
A property with a default value is optional in the input. When it's missing, the default is used. By default, properties equal to their default value are not written, which keeps the output small. Set encodeDefaults = true to write all of them:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class Settings(
val theme: String = "light",
val fontSize: Int = 14,
val nickname: String? = null,
val tags: List<String> = emptyList(),
)
fun main() {
// missing keys take the default value
val s = Json.decodeFromString<Settings>("""{"fontSize": 18}""")
println(s)
// properties equal to their default are not written
println(Json.encodeToString(s))
val verbose = Json { encodeDefaults = true }
println(verbose.encodeToString(s))
}
Settings(theme=light, fontSize=18, nickname=null, tags=[])
{"fontSize":18}
{"theme":"light","fontSize":18,"nickname":null,"tags":[]}
A property without a default value is required, even if it's nullable: {"name": "x"} doesn't decode into a class with val nickname: String? unless you write val nickname: String? = null.
Renaming, required and transient properties
@SerialNamesets the key used in JSON (or the type name, when applied to a class).@Requiredmakes a property with a default value mandatory in the input and always written in the output.@Transient(fromkotlinx.serialization, notkotlin.jvm) excludes a property. It must have a default value, which is used after decoding.
Only properties with a backing field are serialized. Computed properties like label below are ignored:
import kotlinx.serialization.Required
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.Json
@Serializable
data class Product(
@SerialName("product_id") val id: Long,
@SerialName("display_name") val name: String,
@Required val currency: String = "USD",
@Transient val cachedLabel: String = "",
) {
// properties without a backing field are never serialized
val label: String get() = "$name ($currency)"
}
fun main() {
val p = Product(42, "Keyboard", cachedLabel = "ignored")
val json = Json.encodeToString(p)
println(json)
val back = Json.decodeFromString<Product>(json)
println(back)
println(back.label)
try {
Json.decodeFromString<Product>("""{"product_id":1,"display_name":"Mouse"}""")
} catch (e: Exception) {
println("${e::class.simpleName}: ${e.message?.lineSequence()?.first()}")
}
}
{"product_id":42,"display_name":"Keyboard","currency":"USD"}
Product(id=42, name=Keyboard, currency=USD, cachedLabel=)
Keyboard (USD)
MissingFieldException: Field 'currency' is required for type with serial name 'Product', but it was missing at path: $
Configuring Json
Json { ... } creates a configured instance. Create it once and reuse it: it caches information about classes, so creating one per call is wasteful. These options are useful for real-world APIs:
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy
enum class Status { ACTIVE, SUSPENDED }
@Serializable
data class Account(
val userName: String,
val createdAt: String,
val status: Status = Status.ACTIVE,
val loginCount: Int = 0,
)
@OptIn(ExperimentalSerializationApi::class)
val api = Json {
ignoreUnknownKeys = true // skip fields we don't model
coerceInputValues = true // null / unknown enum -> default value
namingStrategy = JsonNamingStrategy.SnakeCase
prettyPrint = true
}
fun main() {
val input = """
{
"user_name": "bob",
"created_at": "2026-10-01",
"status": "DELETED",
"login_count": null,
"avatar_url": "https://example.com/bob.png"
}
"""
val account = api.decodeFromString<Account>(input)
println(account)
println(api.encodeToString(account.copy(loginCount = 3)))
}
Account(userName=bob, createdAt=2026-10-01, status=ACTIVE, loginCount=0)
{
"user_name": "bob",
"created_at": "2026-10-01",
"login_count": 3
}
What happened here:
ignoreUnknownKeysskippedavatar_url. Without it, unknown keys throw an exception. That's a good default for your own data, but too strict for third-party APIs that add fields over time.coerceInputValuesreplaced the unknown enum valueDELETED, and thenullfor a non-nullableInt, with the default values.namingStrategymapsuserNametouser_namein both directions. It's still marked experimental, so it needs an opt-in. If you prefer stable APIs, use@SerialNameon each property.prettyPrintproduces indented output.statusis missing from the output because it equals its default.
Other options worth knowing: explicitNulls = false (don't write null values and treat missing keys as null), isLenient (accept unquoted strings), allowSpecialFloatingPointValues (NaN and Infinity) and allowTrailingComma.
Collections, maps and enums
Standard collections, maps, Pair, Triple and enums are supported out of the box, nested as deep as you like. Use @SerialName on enum entries to change how they are written:
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
enum class Priority {
@SerialName("low") LOW,
@SerialName("high") HIGH,
}
@Serializable
data class Task(val title: String, val priority: Priority, val done: Boolean = false)
@Serializable
data class Board(
val name: String,
val columns: Map<String, List<Task>>,
val labels: Set<String>,
val owner: Pair<String, Int>,
)
fun main() {
val board = Board(
name = "Sprint 12",
columns = mapOf(
"todo" to listOf(Task("Write docs", Priority.LOW)),
"done" to listOf(Task("Fix login", Priority.HIGH, done = true)),
),
labels = setOf("backend", "urgent"),
owner = "ann" to 7,
)
val json = Json.encodeToString(board)
println(json)
println(Json.decodeFromString<Board>(json) == board)
// top-level collections work too
val tasks = Json.decodeFromString<List<Task>>(
"""[{"title":"A","priority":"high"},{"title":"B","priority":"low","done":true}]"""
)
println(tasks)
println(Json.encodeToString(mapOf(1 to "one", 2 to "two")))
}
{"name":"Sprint 12","columns":{"todo":[{"title":"Write docs","priority":"low"}],"done":[{"title":"Fix login","priority":"high","done":true}]},"labels":["backend","urgent"],"owner":{"first":"ann","second":7}}
true
[Task(title=A, priority=HIGH, done=false), Task(title=B, priority=LOW, done=true)]
{"1":"one","2":"two"}
JSON object keys are always strings, so primitive map keys are converted to strings. Enums only need @Serializable when you use @SerialName on their entries.
Polymorphism with sealed classes
When a property or list has an interface or sealed type, the decoder must know which concrete class to create. For sealed classes and interfaces, kotlinx.serialization handles this automatically by adding a "type" discriminator field:
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
sealed interface Event {
val at: Long
}
@Serializable
@SerialName("click")
data class Click(override val at: Long, val x: Int, val y: Int) : Event
@Serializable
@SerialName("key")
data class KeyPress(override val at: Long, val key: String) : Event
@Serializable
@SerialName("logout")
data object Logout : Event {
override val at: Long = 0
}
fun main() {
val events: List<Event> = listOf(Click(100, 10, 20), KeyPress(105, "Enter"), Logout)
val json = Json.encodeToString(events)
println(json)
val back = Json.decodeFromString<List<Event>>(json)
for (e in back) {
val text = when (e) {
is Click -> "click at ${e.x},${e.y}"
is KeyPress -> "key ${e.key}"
Logout -> "logout"
}
println(text)
}
val custom = Json { classDiscriminator = "kind" }
println(custom.encodeToString<Event>(KeyPress(200, "Esc")))
// serializing via the concrete type omits the discriminator
println(Json.encodeToString(KeyPress(200, "Esc")))
}
[{"type":"click","at":100,"x":10,"y":20},{"type":"key","at":105,"key":"Enter"},{"type":"logout"}]
click at 10,20
key Enter
logout
{"kind":"key","at":200,"key":"Esc"}
{"at":200,"key":"Esc"}
@SerialName on a class sets the discriminator value. Without it, the fully qualified class name is used, which breaks your data format when you rename or move a class. classDiscriminator changes the name of the field. The discriminator is only added when the static type is the sealed type: encoding a KeyPress value directly produces plain JSON.
For open (non-sealed) class hierarchies you have to register subclasses yourself in a SerializersModule with polymorphic(Base::class) { subclass(Impl::class) } and pass it as serializersModule to Json { }. Sealed types are simpler and checked at compile time, so prefer them.
Custom serializers
Classes you don't own, like java.time.LocalDate or java.math.BigDecimal, can't be annotated with @Serializable. Write a KSerializer that converts the value to a primitive and back, and attach it to the property with @Serializable(with = ...):
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import java.math.BigDecimal
import java.time.LocalDate
object LocalDateSerializer : KSerializer<LocalDate> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("java.time.LocalDate", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: LocalDate) =
encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder): LocalDate =
LocalDate.parse(decoder.decodeString())
}
// store money as a string so no precision is lost
object BigDecimalSerializer : KSerializer<BigDecimal> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("java.math.BigDecimal", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: BigDecimal) =
encoder.encodeString(value.toPlainString())
override fun deserialize(decoder: Decoder): BigDecimal =
BigDecimal(decoder.decodeString())
}
@Serializable
data class Invoice(
val number: String,
@Serializable(with = LocalDateSerializer::class) val issued: LocalDate,
@Serializable(with = BigDecimalSerializer::class) val total: BigDecimal,
)
fun main() {
val inv = Invoice("INV-7", LocalDate.of(2026, 10, 17), BigDecimal("1999.90"))
val json = Json.encodeToString(inv)
println(json)
val back = Json.decodeFromString<Invoice>(json)
println(back)
println(back.issued.dayOfWeek)
}
{"number":"INV-7","issued":"2026-10-17","total":"1999.90"}
Invoice(number=INV-7, issued=2026-10-17, total=1999.90)
SATURDAY
Storing BigDecimal as a string is deliberate: JSON numbers are often parsed as double by other languages, which loses precision for money amounts.
Annotating every property gets repetitive. @file:UseSerializers applies a serializer to every use of a type in a file, including inside collections. Value classes are serialized as their underlying value, and their init block validates decoded data:
@file:UseSerializers(LocalDateSerializer::class)
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import java.time.LocalDate
object LocalDateSerializer : KSerializer<LocalDate> {
override val descriptor = PrimitiveSerialDescriptor("java.time.LocalDate", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: LocalDate) = encoder.encodeString(value.toString())
override fun deserialize(decoder: Decoder): LocalDate = LocalDate.parse(decoder.decodeString())
}
@Serializable
data class Trip(val from: LocalDate, val to: LocalDate, val stops: List<LocalDate>)
@Serializable
@JvmInline
value class Email(val value: String) {
init { require('@' in value) { "invalid email: $value" } }
}
@Serializable
data class Contact(val name: String, val email: Email)
fun main() {
val d = LocalDate.of(2026, 7, 1)
println(Json.encodeToString(Trip(d, d.plusDays(10), listOf(d.plusDays(3)))))
// value classes are encoded as their underlying value
println(Json.encodeToString(Contact("Ann", Email("ann@example.com"))))
try {
Json.decodeFromString<Contact>("""{"name":"Bob","email":"bob"}""")
} catch (e: IllegalArgumentException) {
println("rejected: ${e.message}")
}
}
{"from":"2026-07-01","to":"2026-07-11","stops":["2026-07-04"]}
{"name":"Ann","email":"ann@example.com"}
rejected: invalid email: bob
For types that should be serialized differently depending on the Json instance, mark the property @Contextual and register the serializer with serializersModule = SerializersModule { contextual(LocalDate::class, LocalDateSerializer) }.
Working with JSON trees
When the structure isn't known in advance, or you only need a few fields from a large document, parse into a JsonElement tree instead of a class. To build JSON without defining a class, use buildJsonObject:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject
fun main() {
val text = """{"repo":"kotlinx.serialization","stars":5600,"topics":["json","kotlin"],"owner":{"login":"Kotlin"}}"""
val root = Json.parseToJsonElement(text).jsonObject
println(root["repo"]!!.jsonPrimitive.content)
println(root["stars"]!!.jsonPrimitive.int + 1)
println(root["topics"]!!.jsonArray.map { it.jsonPrimitive.content })
println(root["owner"]!!.jsonObject["login"])
println(root["missing"])
val request = buildJsonObject {
put("query", "serialization")
put("limit", 10)
putJsonArray("langs") { add("kotlin"); add("java") }
putJsonObject("sort") { put("field", "stars"); put("desc", true) }
}
println(request)
}
kotlinx.serialization
5601
[json, kotlin]
"Kotlin"
null
{"query":"serialization","limit":10,"langs":["kotlin","java"],"sort":{"field":"stars","desc":true}}
jsonPrimitive.content returns the raw string value, while printing a JsonElement prints it as JSON (with quotes). You can convert a tree to a class with Json.decodeFromJsonElement<T>(element).
Handling errors
Invalid input throws a SerializationException (a subclass of IllegalArgumentException). The message includes the JSON path of the problem, which is useful in error responses and logs:
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
@Serializable
data class Point(val x: Int, val y: Int)
fun tryParse(input: String) {
try {
println(Json.decodeFromString<Point>(input))
} catch (e: SerializationException) {
println("${e::class.simpleName}: ${e.message?.lineSequence()?.first()}")
}
}
fun main() {
tryParse("""{"x":1,"y":2}""")
tryParse("""{"x":1}""")
tryParse("""{"x":1,"y":"two"}""")
tryParse("""{"x":1,"y":2,"z":3}""")
tryParse("""{"x":1,"y":2""")
}
Point(x=1, y=2)
MissingFieldException: Field 'y' is required for type with serial name 'Point', but it was missing at path: $
JsonDecodingException: Unexpected JSON token at offset 12: Unexpected symbol 't' in numeric literal at path: $.y
JsonDecodingException: Unexpected JSON token at offset 14: Encountered an unknown key 'z' at path: $
JsonDecodingException: Expected end of the object '}', but had 'EOF' instead at path: $
Always catch SerializationException when decoding data you don't control, like HTTP request bodies or files edited by users.
Binary formats: CBOR and ProtoBuf
The same @Serializable classes work with binary formats. They are smaller and faster to parse than JSON, but not human-readable. Both formats are still marked experimental:
@file:OptIn(ExperimentalSerializationApi::class)
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
import kotlinx.serialization.json.Json
import kotlinx.serialization.protobuf.ProtoBuf
import kotlinx.serialization.protobuf.ProtoNumber
@Serializable
data class Reading(
@ProtoNumber(1) val sensor: String,
@ProtoNumber(2) val celsius: Double,
@ProtoNumber(3) val samples: List<Int>,
)
fun ByteArray.hex() = joinToString("") { "%02x".format(it) }
fun main() {
val r = Reading("t-01", 21.5, listOf(1, 2, 3))
val json = Json.encodeToString(r).encodeToByteArray()
val cbor = Cbor.encodeToByteArray(r)
val proto = ProtoBuf.encodeToByteArray(r)
println("json: ${json.size} bytes")
println("cbor: ${cbor.size} bytes")
println("proto: ${proto.size} bytes ${proto.hex()}")
println(Cbor.decodeFromByteArray<Reading>(cbor))
println(ProtoBuf.decodeFromByteArray<Reading>(proto))
}
json: 50 bytes
cbor: 44 bytes
proto: 21 bytes 0a04742d3031110000000000803540180118021803
Reading(sensor=t-01, celsius=21.5, samples=[1, 2, 3])
Reading(sensor=t-01, celsius=21.5, samples=[1, 2, 3])
ProtoBuf output is the smallest because it uses field numbers instead of names. @ProtoNumber fixes those numbers so the format stays compatible when you reorder or add properties, and lets you match .proto schemas used by other languages. CBOR keeps the property names, so it's a drop-in binary replacement for JSON. See Bytes and binary data for more on working with ByteArray.
Reading and writing files and streams
For large data, encode directly to an OutputStream and decode from an InputStream instead of building a String in memory. decodeToSequence reads a stream of JSON objects (newline-delimited or a top-level array) lazily, one at a time:
@file:OptIn(ExperimentalSerializationApi::class)
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.decodeToSequence
import kotlinx.serialization.json.encodeToStream
import java.io.File
@Serializable
data class LogEntry(val level: String, val msg: String)
fun main() {
val file = File.createTempFile("entries", ".json")
val entries = listOf(LogEntry("INFO", "started"), LogEntry("WARN", "disk 91%"))
file.outputStream().use { Json.encodeToStream(entries, it) }
println(file.readText())
val loaded: List<LogEntry> = file.inputStream().use { Json.decodeFromStream(it) }
println(loaded)
// newline-delimited JSON, read lazily one object at a time
file.writeText(entries.joinToString("\n") { Json.encodeToString(it) })
file.inputStream().use { input ->
Json.decodeToSequence<LogEntry>(input).forEach { println("${it.level}: ${it.msg}") }
}
file.delete()
}
[{"level":"INFO","msg":"started"},{"level":"WARN","msg":"disk 91%"}]
[LogEntry(level=INFO, msg=started), LogEntry(level=WARN, msg=disk 91%)]
INFO: started
WARN: disk 91%
java.io.Serializable
Kotlin classes can implement java.io.Serializable and be written with ObjectOutputStream. You mostly need this for interop with Java APIs that require it: Android Bundles and Intent extras, servlet sessions, or some caching and distributed computing frameworks. Mark fields to skip with @Transient (here it's kotlin.jvm.Transient, the JVM transient modifier):
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
data class Session(
val user: String,
val roles: List<String>,
@Transient val password: String? = null, // kotlin.jvm.Transient
) : Serializable {
companion object {
private const val serialVersionUID = 1L
}
}
fun toBytes(obj: Any): ByteArray {
val out = ByteArrayOutputStream()
ObjectOutputStream(out).use { it.writeObject(obj) }
return out.toByteArray()
}
fun fromBytes(bytes: ByteArray): Any =
ObjectInputStream(ByteArrayInputStream(bytes)).use { it.readObject() }
fun main() {
val s = Session("ann", listOf("admin", "dev"), password = "hunter2")
val bytes = toBytes(s)
println("${bytes.size} bytes")
val back = fromBytes(bytes) as Session
println(back)
println(back == s)
}
212 bytes
Session(user=ann, roles=[admin, dev], password=null)
false
A transient field is not written. After deserialization it's null (or 0 / false), because Java serialization doesn't call the constructor and doesn't apply Kotlin default values. That's why the restored session isn't equal to the original. Declare a serialVersionUID so that compatible changes to the class don't break reading old data; see Serializable and serialVersionUid in Kotlin for details.
Every property type must be Serializable too. Lists, sets and maps created by listOf, setOf and mapOf are, and so are String, numbers and kotlin.Pair, but lambdas and most custom classes need care.
Objects and singletons
Java deserialization always creates a new instance, even for a Kotlin object. To keep the singleton unique, add a readResolve method that returns the existing instance:
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
object Plain : Serializable
object Registry : Serializable {
private fun readResolve(): Any = Registry // return the existing instance
}
data object Marker : Serializable
fun roundTrip(obj: Any): Any {
val out = ByteArrayOutputStream()
ObjectOutputStream(out).use { it.writeObject(obj) }
return ObjectInputStream(ByteArrayInputStream(out.toByteArray())).use { it.readObject() }
}
fun main() {
val p = roundTrip(Plain)
println("Plain: same=${p === Plain} equal=${p == Plain}")
val r = roundTrip(Registry)
println("Registry: same=${r === Registry} equal=${r == Registry}")
val m = roundTrip(Marker)
println("Marker: same=${m === Marker} equal=${m == Marker}")
}
Plain: same=false equal=false
Registry: same=true equal=true
Marker: same=false equal=true
A data object generates an equals that treats every instance of the type as equal, so == works after deserialization, but there's still a second instance. Add readResolve when identity matters.
Security
Never deserialize data from untrusted sources with ObjectInputStream. Deserialization can instantiate any Serializable class on the classpath, and attackers have used chains of such classes to execute arbitrary code. If you must read Java-serialized data, restrict the allowed classes with an ObjectInputFilter:
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InvalidClassException
import java.io.ObjectInputFilter
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
data class Point(val x: Int, val y: Int) : Serializable
fun serialize(obj: Any): ByteArray =
ByteArrayOutputStream().also { out -> ObjectOutputStream(out).use { it.writeObject(obj) } }.toByteArray()
fun safeRead(bytes: ByteArray): Any {
// allow only Point (plus limits on graph size); reject everything else
val filter = ObjectInputFilter.Config.createFilter("Point;maxdepth=5;maxbytes=10000;!*")
return ObjectInputStream(ByteArrayInputStream(bytes)).use {
it.setObjectInputFilter(filter)
it.readObject()
}
}
fun main() {
println(safeRead(serialize(Point(1, 2))))
try {
safeRead(serialize(java.util.Date(0)))
} catch (e: InvalidClassException) {
println("rejected: ${e.message}")
}
}
Point(x=1, y=2)
rejected: filter status: REJECTED
The filter pattern allows Point, limits object graph depth and stream size, and rejects (!*) every other class. The better solution is to avoid Java serialization for anything that crosses a trust boundary and use JSON or ProtoBuf with kotlinx.serialization, which only creates the classes you ask for.
Java serialization can also be used to make deep copies of objects; see Copying and cloning.
Summary
- Use kotlinx.serialization: add the
plugin.serializationGradle plugin and a format library, mark classes with@Serializable, and callJson.encodeToString/Json.decodeFromString<T>. - Properties with default values are optional in the input; use
@SerialName,@Requiredand@Transientto control the format. - Create one configured
Jsoninstance and reuse it;ignoreUnknownKeysandcoerceInputValuesmake decoding third-party data robust. - Use sealed classes with
@SerialNamefor polymorphic data. - Write a
KSerializerfor types you don't own, likeLocalDateandBigDecimal. - Use
JsonElementfor dynamic JSON, and catchSerializationExceptionfor invalid input. - Switch to CBOR or ProtoBuf for compact binary data without changing your classes.
- Use
java.io.Serializableonly for Java interop, addreadResolveto serializable objects, and never deserialize untrusted data withObjectInputStream.