Kotlinx.serialization is a powerful multiplatform serialization library for Kotlin, but it requires a compiler plugin to automatically generate serializers for classes marked with @Serializable[1][2][3]. This compiler plugin dependency can sometimes be a hurdle in simpler scripting environments like .main.kts[4].
Here are some simple Kotlin JSON libraries that don't strictly require compiler plugin support to be compatible with .main.kts[4] scripting, often relying on reflection or providing alternative mechanisms:
-
Moshi: Moshi is a modern JSON library for Kotlin and Java that uses reflection to serialize and deserialize data classes[5][6]. While it can use Kotlin code generation (which acts like a compiler plugin), it also supports a reflection-based approach with KotlinJsonAdapterFactory[5]. Reflection allows it to work with Kotlin classes without needing a compiler plugin to generate adapters[6].
-
Gson: Gson is another popular Java JSON library that works well with Kotlin. It primarily uses reflection for serialization and deserialization[6][7]. You can use Gson in .main.kts[4] scripts without requiring a compiler plugin. While it might be slightly slower than libraries that use code generation, it's a viable option for scripting where performance isn't the absolute critical factor[7].
-
JsonDsl: This library is mentioned in the context of Kotlin scripting for creating DSLs (Domain Specific Languages) that can model JSON[8]. It allows creating Kotlin classes with type-safe properties and a runtime-modifiable map, which can be useful for working with JSON data within scripts without relying on a compiler plugin for serialization[8].
-
Essential-kson: Described as a minimalistic JSON parser adapted from Gson, essential-kson supports various platforms, including JVM[9]. It is published to Maven Central and can be used directly without a compiler plugin, similar to how kotlinx.serialization can be used in some cases[9]. It focuses on raw performance and memory optimization, making it suitable for prototyping and Kotlin scripts[9].
While Kotlinx.serialization is the official Kotlin serialization framework and is generally recommended, its compiler plugin requirement can complicate its use in simple .main.kts[4] scripts. Libraries like Moshi and Gson offer reflection-based alternatives that work without the need for a compiler plugin, making them easier to integrate into scripting environments[5][6][7]. Other libraries like JsonDsl and essential-kson also offer options for handling JSON in Kotlin scripts without relying on the kotlinx.serialization compiler plugin[8][9].