# JSON5 for Kotlin and JVM: Libraries and Gradle | JSON5.dev


Source: https://json5.dev/kotlin/

---

# JSON5 for Kotlin and the JVM: Libraries and Gradle

Decode JSON5 straight into Kotlin data classes, edit a config file without losing its comments, and know which JVM libraries to reach for.

Kotlin has one actively maintained JSON5 library built on kotlinx.serialization, `li.songe:json5`, plus a few older or experimental ones. Every Java library from the [Java guide](https://json5.dev/java/) also works from Kotlin.

Below you will find Gradle setup, the API read from the published sources, the options kotlinx.serialization already gives you, and the traps in each. No Kotlin compiler was available here, so samples are checked against sources and READMEs, not compiled.

![A JSON5 config card flowing into a Kotlin data class beside a Gradle build script on a workbench under a warm lamp](https://json5.dev/img/hero/kotlin.png)

**TL;DR:** Add `li.songe:json5:0.8.0` and `kotlinx-serialization-json`, then call `json.decodeFromJson5String<T>(text)`. It runs on the JVM, JavaScript, Wasm and several native targets, parses comments and trailing commas, and is the only Kotlin library found that can edit a file and keep its comments. On an existing Jackson or Gson stack, use the Java route instead.

[Which Library](#choose) [Gradle](#gradle) [Parse](#parse) [Write and Edit](#write) [API](#api) [Java Libraries](#jvm) [No Library](#builtin) [Errors](#errors) [Conformance](#conformance) [Pitfalls](#pitfalls) [FAQ](#faq) [Sources](#references)

![Kotlin logo](https://json5.dev/images/tech/kotlin.png)

## Which Library?

I searched GitHub and Maven Central on November 29, 2026 for Kotlin JSON5 libraries. Maven Central's search index was stale that day, so versions and dates below come from each library's `maven-metadata.xml` and release pages instead. Four Kotlin-first libraries turned up:

Library

Coordinates

Version

Released

License

Platforms

Status

**kotlin-json5** (lisonge)

`li.songe:json5`

0.8.0

09-08-2026

Apache-2.0

JVM, JS, Wasm, iOS, macOS (Apple silicon), Linux, tvOS, watchOS

Active: four releases since November 2025

**json5k** (xn32)

`io.github.xn32:json5k`

0.3.0

03-12-2023

Apache-2.0

JVM, Linux x64, macOS, iOS, Windows x64

Repository archived

**json5-kotlin** (hossain-khan)

`hossain.dev:json5kt` on GitHub Packages

1.2.0

06-10-2025

MIT

JVM

Self-described experimental proof of concept

**Cason** (cao-awa)

`com.github.cao-awa:cason` on JitPack

1.0.37

10-07-2026

GPL-3.0

JVM

Active; JSON and JSON5 in one DSL

### kotlin-json5

Built on kotlinx.serialization, so it decodes into your `@Serializable` classes and produces `JsonElement` trees. It also offers a lossless document model with comments, source ranges and diagnostics, a formatter, and a structural editor. Its dependencies are `kotlinx-serialization-json` (1.11.0 or later) and the Kotlin standard library; 0.8.0 was built with Kotlin 2.4.10.

### json5k

Also built on kotlinx.serialization, with a spec-1.0.0 compliance claim, polymorphic types, configurable class discriminators, a `@SerialComment` annotation to write comments for class properties, and duplicate-key rejection. Its README shows deserialization errors that carry a line and column, such as `DuplicateKeyError: duplicate key 'age' at position 1:26`. The README also calls it experimental, the last release is from March 2023, and the repository is archived. Fine to read for ideas; I would not start a new project on it.

### json5-kotlin

Parses to a typed `JSON5Value` tree and integrates with kotlinx.serialization. Its README opens with a caution that it is an experimental proof of concept developed entirely with agentic AI. It is published to GitHub Packages, which requires a personal access [token](https://json5.dev/glossary/#punctuator) with the `read:packages` permission even to download, so it is awkward for CI. Not recommended for production.

### Cason

A hand-written state-machine parser with its own object model and a DSL, not kotlinx.serialization. It is licensed GPL-3.0, so using it in a distributed application carries the GPL's obligations. Its README makes speed claims that I did not verify. It reads JSON5 comments and [trailing commas](https://json5.dev/glossary/#trailing-comma).

Other routes: the Java libraries covered next, and for an [application config](https://json5.dev/config/) that needs no JSON5 syntax beyond comments and trailing commas, kotlinx.serialization's own options (see [No Library at All](#builtin)). The broader field is on the [implementations](https://json5.dev/implementations/) page.

![Download icon](https://json5.dev/images/icons/download.png)

## Gradle Setup

The serialization compiler plugin is required for `@Serializable` classes. On November 29, 2026 the newest non-prerelease Kotlin on Maven Central was 2.4.21 (2.5.0 was in release-candidate stage), and the newest `kotlinx-serialization-json` was 1.13.0, published November 11, 2026.

`// build.gradle.kts plugins { kotlin("jvm") version "2.4.21" kotlin("plugin.serialization") version "2.4.21" } repositories { mavenCentral() } dependencies { implementation("li.songe:json5:0.8.0") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.13.0") }`

For a Kotlin Multiplatform project, declare the dependency once in `commonMain` and Gradle resolves the right variant per target:

`kotlin { sourceSets { commonMain.dependencies { implementation("li.songe:json5:0.8.0") } } }`

Java 11+

JVM target of the published jar

Apache-2.0

License of kotlin-json5

21 KB

Size of the 0.8.0 JVM jar

Android: the published Gradle metadata lists no Android-specific variant, and I found no Android documentation for any library on this page. A plain JVM library often works in an Android module, but test it on a device before you rely on it.

![Kotlin logo](https://json5.dev/images/tech/kotlin.png)

## Parse Into Data Classes

**How these samples were checked:** not compiled or run. Each result in a comment follows from the library's source or README. Compile them once in your own project before relying on them.

`decodeFromJson5String` is an extension on kotlinx.serialization's `Json`. It parses the text to a `JsonElement` and then calls the ordinary decoder, so everything you configure on `Json` (such as `ignoreUnknownKeys`) still applies.

`import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import li.songe.json5.decodeFromJson5String @Serializable data class Server(val host: String, val port: Int, val tags: List<String> = emptyList()) @Serializable data class AppConfig(val name: String, val server: Server) val json = Json { ignoreUnknownKeys = true } val config = json.decodeFromJson5String<AppConfig>(""" { // service settings name: 'billing', server: { host: 'localhost', port: 0x1F90, tags: ['eu', 'prod',], }, } """.trimIndent()) println(config) // AppConfig(name=billing, server=Server(host=localhost, port=8080, tags=[eu, prod]))`

The hexadecimal `0x1F90` becomes `8080` because the scanner converts hex literals to a decimal string of any length before kotlinx.serialization sees them.

### Read a file

`import java.nio.file.Files import java.nio.file.Path val text = Files.readString(Path.of("config/app.json5")) // UTF-8 by default val config = json.decodeFromJson5String<AppConfig>(text)`

### Tree access

When you do not want classes, `Json5.parseToJsonElement` returns kotlinx.serialization's tree. It ignores comments, because a `JsonElement` cannot hold them.

`import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import li.songe.json5.Json5 val element = Json5.parseToJsonElement("{ name: 'billing', }") element.jsonObject["name"]?.jsonPrimitive?.content // "billing"`

### Parsing that never throws

`Json5.parseToDocument` recovers from bad or half-typed input and reports problems as diagnostics instead of throwing. That is what an editor integration wants.

`val document = Json5.parseToDocument("{a:1,]{") document.isValid // false for (d in document.diagnostics) { println("${d.code} at ${d.range.start}: ${d.message}") }`

![Edit icon](https://json5.dev/images/icons/edit.png)

## Write, Format and Edit

Most languages cannot write JSON5 that a person would want to read. kotlin-json5 can encode, format, and also change one value inside a file while leaving every comment and unrelated line untouched.

### Encode

The default `Json5EncoderConfig` is compact, uses single quotes, leaves keys unquoted when they are valid identifiers, and writes no trailing comma. Change any of them:

`import li.songe.json5.Json5EncoderConfig import li.songe.json5.Json5QuoteStrategy import li.songe.json5.encodeToJson5String val config = Json5EncoderConfig( indent = " ", // spaces or tabs only; "" is compact quoteStrategy = Json5QuoteStrategy.PreferDouble, unquotedKey = true, trailingComma = true, ) val text: String = json.encodeToJson5String(appConfig, config)`

Quote strategies are `Single`, `Double`, `PreferSingle` and `PreferDouble`. The `Prefer` variants switch delimiter when that avoids an escape. You can also encode a single literal with `Json5.encodeString` or a property name with `Json5.encodeKey`.

### Format a file you already have

`Json5.format` re-indents text and preserves comments and raw literals such as `0x1f90` by default. `Json5FormatConfig` controls indent, [line separator](https://json5.dev/glossary/#line-separator), trailing commas, final newline and optional re-quoting. `Json5.formatToEdits` returns the change as a list of text edits for an editor.

`val tidy = Json5.format("{port:0x1f90,// default\nenabled:true,}")`

### Edit one value, keep the comments

Edits are source-aware: only the selected range is replaced. Navigate with `Json5Path`, and each call returns a result that carries the new `text` and the updated `document`.

`import kotlinx.serialization.json.JsonPrimitive import li.songe.json5.Json5 import li.songe.json5.Json5Path import li.songe.json5.addCommentBefore import li.songe.json5.set val source = """ { // server port port: 8080, } """.trimIndent() val changed = Json5.parseToDocument(source).set(Json5Path["port"], JsonPrimitive(9090)) println(changed.text) // same text, comment intact, 8080 replaced by 9090 // run a second edit on the document the first one returned val commented = changed.document.addCommentBefore(Json5Path["port"], "Restart to apply")`

The editing API also removes values, renames or adds properties, inserts array elements, and adds or removes comments. Two rules from its README: the edit list in each result is relative to the document that operation started from, so never concatenate lists from chained operations (use the final `text`); and the high-level API cannot change the content of an existing comment, so replace the whole comment range with a `Json5TextEdit` instead. Editing a hand-maintained file this way is rare: Python has `json-five` for [round trips](https://json5.dev/glossary/#round-trip) (see the [Python guide](https://json5.dev/python/)), while the Ruby gems cannot do it (see the [Ruby guide](https://json5.dev/ruby/)).

![Code icon](https://json5.dev/images/icons/code.png)

## API Reference From Source

Signatures below come from the 0.8.0 sources jar on Maven Central, package `li.songe.json5`.

Call

Returns

Notes

`Json5.parseToJsonElement(input: CharSequence)`

`JsonElement`

Throws `Json5ParseException`. Comments are dropped.

`Json5.parseToDocument(input: CharSequence)`

`Json5Document`

Never throws for bad input; see `diagnostics`, `isValid`, `requireValid()`, `toJsonElement()`, `comments`, `tokens`.

`Json.decodeFromJson5String<T>(value: CharSequence)`

`T`

Extension on kotlinx.serialization `Json`.

`Json5.encodeToString(element, config)`

`String`

Takes a `JsonElement` and a `Json5EncoderConfig`.

`Json.encodeToJson5String(value, config)`

`String`

Extension; encodes any serializable value.

`Json5.format(input, config)` and `Json5.formatToEdits(input, config)`

`String` and `List<Json5TextEdit>`

Valid input only; throws `Json5ParseException` otherwise.

`Json5.scanSyntax(input, ignoreWhitespace)`

`Json5SyntaxTokens` or a callback per span

Tolerant scan for syntax highlighting; accepts invalid input.

`Json5.encodeString(value, config)` and `Json5.encodeKey(key, config)`

`String`

One literal or one property name.

`Json5Document.set / remove / renameProperty / putProperty / insertArrayElement / appendArrayElement / addCommentBefore / addCommentAfter / removeComment`

`Json5EditResult`

Extension functions in the same package; each result holds `text`, `edits` and `document`.

`Json5EncoderConfig` fields: `indent` (default empty), `quoteStrategy` (default `Single`), `unquotedKey` (default true), `trailingComma` (default false). `Json5FormatConfig` fields: `indent` (default two spaces), `lineSeparator`, `trailingComma`, `finalNewline` (each defaults to `Preserve`), `quoteStrategy` (default null, meaning keep original quotes) and `unquotedKey`.

![Java logo](https://json5.dev/images/tech/java.png)

## Using the Java Libraries From Kotlin

Kotlin calls Java libraries directly, so everything on the [Java guide](https://json5.dev/java/) is available. Reach for one when you are on a Jackson or Gson stack already, or when you need a plain JVM tree API with a spec-complete parser.

### json5-java

`de.marhali:json5-java` 3.0.0 (published September 23, 2025) is a Gson-style tree library that claims full spec support, requires Java 11, has no runtime dependencies, and can parse and write comments.

`// build.gradle.kts: implementation("de.marhali:json5-java:3.0.0") import de.marhali.json5.Json5 val json5 = Json5.builder { it.quoteless().quoteSingle().parseComments().writeComments().prettyPrinting().build() } val element = json5.parse("{ 'key': 'value', 'array': ['first val','second val'] }") val text: String = json5.serialize(element)`

The result is a `Json5Element` tree, not a data class. For typed access, use the kotlinx.serialization route above or Jackson below.

### Jackson with the Kotlin module

`jackson-module-kotlin` 2.23.0 (November 2026) adds data class support. Combine it with the relaxed read features from the Java guide. There is also a 3.x line under the `tools.jackson` group; check its package names before copying imports.

`// implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.23.0") import com.fasterxml.jackson.core.json.JsonReadFeature import com.fasterxml.jackson.module.kotlin.jsonMapper import com.fasterxml.jackson.module.kotlin.kotlinModule import com.fasterxml.jackson.module.kotlin.readValue val mapper = jsonMapper { addModule(kotlinModule()) enable(JsonReadFeature.ALLOW_JAVA_COMMENTS) enable(JsonReadFeature.ALLOW_TRAILING_COMMA) enable(JsonReadFeature.ALLOW_SINGLE_QUOTES) enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES) } val config: AppConfig = mapper.readValue(text)`

This reads the common conveniences but not hexadecimal numbers: the Java guide's [coverage table](https://json5.dev/java/) lists what Jackson can and cannot do.

### Gson

Gson 2.15.0 (October 24, 2026) has a lenient mode, `GsonBuilder().setLenient().create()`, that is a single switch for forgiving input rather than a JSON5 parser. It accepts things JSON5 does not and cannot be tuned feature by feature. Prefer a real JSON5 library.

![Lightweight icon](https://json5.dev/images/icons/lightweight.png)

## No Library at All: kotlinx.serialization Options

kotlinx.serialization's own `Json` has switches that cover part of JSON5. The Kotlin documentation lists them without an experimental marker:

Option

What it accepts

`allowComments = true`

`//` line comments and `/* */` block comments

`allowTrailingComma = true`

A trailing comma in arrays and objects

`isLenient = true`

Unquoted keys, unquoted string values and enum values; it also lets a quoted `"9000"` decode into an `Int`

`allowSpecialFloatingPointValues = true`

`NaN` and the infinities

`val relaxed = Json { allowComments = true allowTrailingComma = true isLenient = true allowSpecialFloatingPointValues = true }`

The documentation I read does not mention single-quoted strings, hexadecimal numbers, a [leading](https://json5.dev/glossary/#leading-decimal-point) plus sign, `.5` or `5.`, or [line continuations](https://json5.dev/glossary/#line-continuation), so a genuine JSON5 file will fail on those. This is a JSONC-plus setup, a useful middle ground when the files are yours (see [JSON5 versus JSONC](https://json5.dev/compare/jsonc/)). Note that `isLenient` also loosens types, which JSON5 does not, so it can hide mistakes in your data.

![Bug icon](https://json5.dev/images/icons/bug.png)

## Error Handling

kotlin-json5 throws `Json5ParseException`, which extends `IllegalStateException`. It carries a `diagnostic` (code, source range, message) and an `offset`. The message ends with "at index N". It reports a character index, not a line and column, so compute the line yourself if you want to show one.

`import li.songe.json5.Json5ParseException fun loadConfig(text: String): AppConfig = try { json.decodeFromJson5String<AppConfig>(text) } catch (e: Json5ParseException) { val line = text.take(e.offset).count { it == '\n' } + 1 error("config is not valid JSON5 (line $line): ${e.diagnostic.message}") }`

The diagnostic codes are an enum: `UnexpectedCharacter`, `UnexpectedToken`, `ExpectedValue`, `ExpectedProperty`, `ExpectedColon`, `ExpectedCommaOrEnd`, `InvalidNumber`, `InvalidIdentifier`, `InvalidEscape`, `UnclosedString`, `UnclosedBlockComment`, `UnclosedContainer` and `MismatchedClosingToken`.

Two failure layers exist. A syntax error is a `Json5ParseException` from this library. A well-formed document that does not match your class (a missing field, a wrong type) fails inside kotlinx.serialization, with that library's exceptions. Catch both if a bad file should never crash startup. See also the [error reference](https://json5.dev/errors/).

![Test icon](https://json5.dev/images/icons/test.png)

## Conformance: What Each Library Claims

I did not run the official `json5-tests` files against any of these libraries, because no Kotlin toolchain was available. What follows is what each project states and what its source shows. The wider picture is on the [conformance](https://json5.dev/conformance/) page.

-   **kotlin-json5** makes no explicit specification-conformance claim in its README. Its scanner enforces several spec rules: it rejects a decimal with a leading zero ("Decimal numbers must not contain a leading zero"), requires at least one digit after `0x`, accepts `NaN` and `Infinity` with an optional sign, and allows only `\u` escapes inside identifiers. Its test folder has parser, error, formatter, editor and syntax tests. The official corpus is not referenced.
-   **json5k** states compliance with JSON5 1.0.0 and rejects duplicate keys during deserialization. It is archived, so a spec correction will not reach it.
-   **json5-kotlin (hossain-khan)** lists the full feature set in its README. Its repository pulls in the reference implementation and the specification repositories as git submodules; I did not trace which tests use them. The README warns that some functionality may be incomplete or unstable.
-   **Cason** says it supports comments and trailing commas and describes its JSON5 parsing as having "error recovery". No conformance claim is made.

Run the official files through your chosen library in CI: every valid file should decode, and every invalid one should throw.

![Warning icon](https://json5.dev/images/icons/warning.png)

## Things That Will Surprise You

Each item is read from the released source or the project's own documentation, not observed at runtime.

### 1\. Default output is not JSON

The default encoder writes single-quoted strings and unquoted keys. A strict JSON consumer will reject that. If a client needs JSON, serialize with kotlinx.serialization's own `Json`, or choose `Json5QuoteStrategy.Double` and set `unquotedKey = false`.

### 2\. Comments vanish on the tree route

`parseToJsonElement` and `decodeFromJson5String` discard comments, so decode, change and encode rewrites the file without them. Use `parseToDocument` with the editing functions when the file is hand-maintained.

### 3\. Repeated keys: last wins on conversion

The document model keeps duplicate properties, but converting to a `JsonElement` keeps the last value. An edit path with no occurrence index selects the last match. json5k, by contrast, rejects duplicates.

### 4\. Big integers: avoid Number conversions

Parsed numbers are held as text in a `Json5Number`, but its `toLong()` and `toInt()` go through `Double`, which cannot represent every integer above 253. Read such values from `.content` or decode into a type, and do not cast to `Number`.

### 5\. Pin versions that agree

kotlin-json5 0.8.0 was built with Kotlin 2.4.10 and needs kotlinx-serialization-json 1.11.0 or later. A project on an older Kotlin compiler can fail to read its metadata. Pair it with the same or a newer compiler.

### 6\. Windows native is not published

kotlin-json5's published metadata lists JVM, JS, Wasm and Apple, Linux targets but no Windows native target. json5k's README lists `mingwX64`. A multiplatform build that includes Windows native will not resolve kotlin-json5.

### 7\. `isLenient` loosens types too

The Kotlin documentation shows a quoted `"9000"` decoding into an `Int` under `isLenient`. JSON5 would keep that a string. If your files are validated elsewhere, this may be fine; if not, it hides data errors.

### 8\. GitHub Packages needs a token

hossain-khan's json5-kotlin is distributed through GitHub Packages, and its README tells you to supply a GitHub username and a personal access token to resolve it. That makes anonymous CI and open-source builds harder than Maven Central does.

## JSON5 in Kotlin: Common Questions

### Does kotlinx.serialization read JSON5?

Partly. With `allowComments`, `allowTrailingComma` and `isLenient` it reads comments, trailing commas and unquoted keys. It does not document single quotes, hex numbers or line continuations, so use a library for real JSON5.

### Which library for a new project?

`li.songe:json5`, unless you are already on Jackson or Gson, where the Java route avoids a second serialization stack.

### Can I use it in Kotlin Multiplatform?

Yes, for the targets in its published metadata: JVM, JS, Wasm, iOS, macOS on Apple silicon, Linux, tvOS and watchOS. There is no Windows native or Android-specific variant.

### How do I keep comments when my program changes a setting?

Parse with `parseToDocument`, change the value with `set`, and save the result's `text`. Nothing outside the edited range changes.

### Is it safe to parse untrusted JSON5?

The libraries build data and never execute input. I found no documented size or depth limit in any of them, so cap the input length before parsing. The [security tutorial](https://json5.dev/tutorials/security/) covers the details.

### Does Gradle read a `.json5` build file?

No. Gradle's own files stay Kotlin or Groovy. Use a JSON5 file for your application's settings and load it at startup. The [config guides](https://json5.dev/config/) show where tools accept it natively.

## Related Pages

[![Java logo](https://json5.dev/images/tech/java.png)

### Java Guide

json5-java, Jackson and Gson

](https://json5.dev/java/)[![TypeScript logo](https://json5.dev/images/tech/typescript.png)

### TypeScript Guide

Typed config on the other side

](https://json5.dev/typescript/)[![List icon](https://json5.dev/images/icons/list.png)

### Implementations

Libraries across languages

](https://json5.dev/implementations/)

## Sources

(12)

1.  [lisonge/kotlin-json5: README, releases and commit history](https://github.com/lisonge/kotlin-json5)
2.  [Maven Central: li.songe:json5 0.8.0 (pom, Gradle module metadata, sources jar)](https://repo1.maven.org/maven2/li/songe/json5/0.8.0/)
3.  [xn32/json5k: README and releases](https://github.com/xn32/json5k)
4.  [hossain-khan/json5-kotlin: README, releases and submodules](https://github.com/hossain-khan/json5-kotlin)
5.  [cao-awa/Cason: README and releases](https://github.com/cao-awa/Cason)
6.  [Kotlin documentation: Configure JSON serialization (isLenient, allowComments, allowTrailingComma, allowSpecialFloatingPointValues)](https://kotlinlang.org/docs/serialization-json-configuration.html)
7.  [Maven Central metadata: kotlinx-serialization-json](https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-serialization-json/maven-metadata.xml)
8.  [Maven Central metadata: kotlin-stdlib](https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-stdlib/maven-metadata.xml)
9.  [marhali/json5-java: README](https://github.com/marhali/json5-java)
10.  [FasterXML/jackson-module-kotlin: README](https://github.com/FasterXML/jackson-module-kotlin)
11.  [Maven Central metadata: Gson](https://repo1.maven.org/maven2/com/google/code/gson/gson/maven-metadata.xml)
12.  [The JSON5 Data Interchange Format 1.0.0](https://spec.json5.org/)

Last reviewed: November 29, 2026.
