Home › Developer Tools › JSON to Kotlin Data Class

JSON to Kotlin Data Class

Paste a JSON object or API response and get ready-to-use Kotlin data classes with camelCase properties, nullable types and @SerialName, @SerializedName, @Json or @JsonProperty annotations. Everything runs in your browser.

Last updated:

Your JSON is parsed locally in this tab and never uploaded. Tip: Ctrl + Enter generates.

Advertisement
Advertisement

How to use the JSON to Kotlin Data Class

  1. Paste your JSON into the left box, or open a .json file. A sample is loaded so you can see the output right away.
  2. Name the root class and set the package (leave it blank to omit the package line).
  3. Pick your serialization library: kotlinx.serialization, Gson, Moshi, Jackson or none.
  4. Choose nullability and style: nullable properties, = null defaults, Int or Long, val or var, nested classes.
  5. Press Generate Kotlin Classes, then copy the code or download the .kt file into your project.

Example: JSON to Kotlin data classes

This API response has a snake_case key, a nested object, an array of objects and a value that can be null:

{ "user_id": 42, "display_name": "Ada", "avatar": null,
  "posts": [ { "id": 1, "title": "Hello", "score": 4.5 },
             { "id": 2, "title": "Draft", "score": 3, "cover": "a.png" } ] }

With kotlinx.serialization and the default options the generator produces:

@Serializable
data class Root(
    @SerialName("user_id") val userId: Int,
    @SerialName("display_name") val displayName: String,
    val avatar: JsonElement? = null,
    val posts: List<Post>
)

@Serializable
data class Post(
    val id: Int,
    val title: String,
    val score: Double,
    val cover: String? = null
)

score is Double because one item has 4.5, and cover is nullable with a default because only one item has it. avatar is only ever null, so its real type cannot be known: it becomes JsonElement? (or Any? for other libraries). Replace it with String? once you know.

How JSON values map to Kotlin types

JSON valueKotlin type
"text"String
42Int, or Long outside ±2,147,483,647
3.14, 1e6Double
true / falseBoolean
"x" or null, or a missing keyString? = null
{ … }A data class (top-level or nested)
{}JsonObject / Map<String, Any?>
[1, 2] / []List<Int> / List<JsonElement>
[1, "two"] or always nullJsonElement / Any?

Name annotations by library

LibraryClass annotationProperty annotationDecode
kotlinx.serialization@Serializable@SerialName("key")Json.decodeFromString<Root>(text)
Gsonnone@SerializedName("key")Gson().fromJson(text, Root::class.java)
Moshi (codegen)@JsonClass(generateAdapter = true)@Json(name = "key")moshi.adapter(Root::class.java).fromJson(text)
Jacksonnone (register KotlinModule)@JsonProperty("key")jacksonObjectMapper().readValue<Root>(text)
  • Unknown keys: kotlinx.serialization throws on keys that have no property unless you create the parser with Json { ignoreUnknownKeys = true }. Gson and Moshi ignore them; Jackson fails unless FAIL_ON_UNKNOWN_PROPERTIES is disabled.
  • kotlinx.serialization needs its compiler plugin (plugin.serialization in Gradle); Moshi codegen needs KSP or kapt with moshi-kotlin-codegen.
  • Large IDs: keep Long for numeric IDs above 2,147,483,647, such as Twitter-style snowflake IDs.

Frequently asked questions

How are Kotlin property names created from JSON keys?

Each key is split into words at underscores, dashes, spaces and camelCase boundaries and joined in camelCase, so user_name becomes userName and email-notifications becomes emailNotifications. When the property name differs from the key, the generator adds the name annotation of your library (@SerialName, @SerializedName, @Json or @JsonProperty) so decoding still matches the JSON.

Which properties become nullable?

By default a property is nullable (for example String?) when its value is null somewhere in the JSON or when the key is missing from some items of an array. You can also make every property nullable, which is the safest choice for APIs you do not control, or none. With the default option on, nullable properties get = null so a missing key does not fail decoding.

Why do kotlinx.serialization classes need @Serializable?

kotlinx.serialization generates the serializer at compile time with its Gradle plugin, and it only does so for classes marked @Serializable. Values whose type cannot be known, such as a field that is always null or mixes strings and numbers, are typed as JsonElement so they can still be decoded.

Does Gson respect Kotlin default values and non-null types?

Not fully. Unless every property has a default value, Gson creates objects without calling the Kotlin constructor, so a missing key can leave a non-null property holding null and defaults are skipped. If your JSON may omit fields, choose 'All properties' nullable with Gson, or use kotlinx.serialization or Moshi codegen, which honour Kotlin nullability and defaults.

How are numbers typed?

Whole numbers become Int, or Long when any value is outside the 32-bit range (−2,147,483,648 to 2,147,483,647); you can also force Long everywhere. Numbers with a decimal point or exponent become Double. If a field mixes whole and decimal numbers, Double is used.

What happens with a JSON array at the top level?

The item type is generated as a data class and a comment reminds you to decode the JSON as List<Item>, for example Json.decodeFromString<List<Item>>(text). A top-level array of plain values becomes a typealias such as typealias Root = List<String>.

Is my JSON uploaded?

No. Parsing and code generation are plain JavaScript running in this page, so API responses with personal or secret data never leave your device.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON to Swift StructTurn JSON into Swift Codable structs with CodingKeys, optionals and nested types.JSON to TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON to C# ClassConvert JSON to C# classes or records with System.Text.Json or Newtonsoft attributes.JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.JSON to Excel ConverterTurn JSON into a styled .xlsx spreadsheet; nested arrays become their own linked sheets.JSON to CSVConvert JSON data to CSV for spreadsheets.CSV to JSONConvert CSV data to JSON with live preview.Excel to CSVConvert XLSX spreadsheets to CSV.CSV ViewerOpen a CSV or TSV file as a sortable, filterable table.Excel Viewer (XLSX / XLS)Open XLSX, XLS and ODS spreadsheets in your browser without Excel.Line Ending ConverterConvert text and files between CRLF, LF and CR line endings.Markdown to HTMLConvert Markdown to clean HTML with a live editor.XML to JSONConvert XML to JSON with validation.Text Encoding ConverterDetect and convert text file encodings like UTF-8, UTF-16 and Latin-1.JSON ViewerExplore JSON as a collapsible tree, search keys and values and copy any node's path.TTF to WOFF2 ConverterConvert TTF and OTF fonts to WOFF2 or WOFF and get a ready @font-face CSS snippet.Chmod CalculatorConvert Linux file permissions between checkboxes, octal (755) and symbolic (rwxr-xr-x) notation.Morse Code TranslatorTranslate text to Morse code and back, then play it as sound or a blinking light, or save a WAV.HTML Table GeneratorBuild HTML tables in an editable grid with styles, header rows, CSV import and live preview.Hex to Text ConverterConvert hex to text and text to hex with UTF-8 support and space, 0x, \x or comma formats.JSON to XML ConverterConvert JSON to well-formed XML with attributes, arrays and pretty print.JSON to YAML ConverterConvert JSON to clean YAML as you type, with indent, quoting and sort options.YAML to JSON ConverterConvert YAML to pretty or minified JSON, with errors pinned to the exact line.HTML to Markdown ConverterTurn HTML or pasted rich text into clean Markdown with tables and live preview.Markdown Table GeneratorBuild Markdown tables in a grid or paste from Excel/CSV, with alignment and preview.JSON ValidatorCheck JSON with the exact line and column of each error, fix tips and one-click auto-fix.Image to Base64Convert images to Base64 data URIs, CSS backgrounds and HTML img tags in your browser.Base64 to ImagePaste a Base64 string or data URI to preview, identify and download the image.JSON CompareCompare two JSON documents and see every added, removed and changed path.Hex to DecimalConvert hex to decimal instantly with steps and signed mode.Decimal to HexConvert decimal to hex instantly with steps and signed mode.Binary to DecimalConvert binary to decimal instantly with steps and signed mode.Decimal to BinaryConvert decimal to binary instantly with steps and signed mode.Two's Complement CalculatorDecimal to two's complement binary and back for 4-64 bits, with invert-and-add-1 steps.XML to CSV ConverterConvert XML to CSV: detects repeating records, flattens nested data, pick your columns.CSV to XML ConverterConvert CSV to well-formed XML with custom root and row names, escaping and pretty print.TOML to JSON ConverterConvert TOML to JSON and JSON to TOML with a full v1.0 parser and clear error lines.JSON to Go StructTurn JSON into Go structs with inferred types, nested structs and json tags.CSV to Markdown TableConvert CSV to a neatly aligned GitHub Markdown table with column alignment and live preview.CSV TransposeSwap rows and columns of CSV, TSV or pasted spreadsheet data, with delimiter auto-detect.Date Format ConverterConvert any date to ISO 8601, RFC 2822, Unix time and custom strftime, moment or Java patterns.ENV to JSON ConverterConvert .env files to JSON or YAML and JSON back to .env, with quotes and multiline values.File to Base64Convert any file to a Base64 string or data URI with MIME detection, line wrap and download.HTML Table to CSVExtract any table from HTML or page source to CSV, TSV or JSON, with colspan and rowspan handled.IEEE 754 Floating Point ConverterConvert decimals to 32/64-bit IEEE 754 floats: toggle bits, see hex, exact value and rounding error.INI to JSON ConverterConvert INI and CFG files to JSON and JSON back to INI, with sections, arrays and types.IP Address ConverterConvert IPv4 to decimal, hex, binary, octal and back, with class and private/public check.ISBN Converter & ValidatorConvert ISBN-10 to ISBN-13 and back, validate check digits and hyphenate, one or in bulk.JSON Flatten / UnflattenFlatten nested JSON to dot or bracket path keys, or unflatten flat keys back to nested JSON.JSON to Dart ClassTurn JSON into Dart model classes with fromJson, toJson, null safety and nested classes.JSON to Java ClassTurn JSON into Java POJOs or records with Lombok, getters/setters and Jackson or Gson annotations.JSON to Markdown TableTurn a JSON array of objects into a GitHub Markdown table with column picker and alignment.JSON to PHP ArrayConvert JSON to PHP array code (short [] or array()) and PHP arrays back to JSON.JSON to Rust StructTurn JSON into Rust structs with serde derives, rename attributes, Option and Vec types.JSON to SQL ConverterConvert a JSON array of objects to CREATE TABLE and INSERT statements for MySQL, Postgres, SQLite.JSON to TOML ConverterConvert JSON to clean TOML with tables, arrays of tables, inline tables and dates.JSONL to JSON ConverterConvert JSON Lines / NDJSON to a JSON array and back, with line-level error reports.Properties to YAML ConverterConvert Java .properties to nested YAML (application.yml) and YAML back to properties.PX to EM ConverterConvert pixels to em using the parent font size, and em back to px, with conversion tables.Query String to JSONConvert URL query strings to JSON with nested brackets and arrays, and JSON back to a query string.REM to PX ConverterConvert CSS rem values to pixels for any root font size, with a quick 0.25–6rem table.SQL to JSON ConverterConvert SQL INSERT statements and dumps into a JSON array of row objects, with CSV export.TSV to CSV ConverterConvert TSV to CSV and back, or between tab, comma, semicolon and pipe, with correct quoting.TypeScript to JavaScriptConvert TypeScript or TSX to clean JavaScript instantly: strip types, keep or compile JSX.XML to YAML ConverterConvert XML to clean YAML with attributes, text nodes, lists and exact error lines.YAML to XML ConverterConvert YAML to pretty, well-formed XML with custom root, attributes and array item tags.Boolean Algebra SimplifierSimplify boolean expressions or minterm lists to minimal SOP and POS with Quine-McCluskey steps.Compare Excel FilesCompare two Excel spreadsheets cell by cell, highlight changes and export a diff report.
See all 129 Data & File Format Converters →