Home › Developer Tools › JSON to Dart Class

JSON to Dart Class

Paste a JSON object or API response and get null-safe Dart model classes for Flutter: final fields, a named constructor, fromJson and toJson, copyWith and a class for every nested object. Choose plain Dart or json_serializable 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 Dart 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, for example User or ProductResponse.
  3. Choose the output style: plain Dart with hand-written fromJson/toJson, or json_serializable annotations for build_runner.
  4. Set the options: which fields are nullable, field naming, final fields, const constructor, copyWith, toString and DateTime parsing.
  5. Copy or download the .dart file into your Flutter project and call User.fromJson(jsonDecode(body)).

Example: JSON to a Dart model class

Given this JSON with snake_case keys, a date, a nested object and a list:

{ "id": 7, "full_name": "Ada", "price": 3.5, "created_at": "2024-05-01T09:30:00Z",
  "tags": ["a", "b"], "owner": { "id": 1, "email": null } }

the plain Dart output (copyWith omitted here) looks like this:

class Root {
  const Root({
    required this.id,
    required this.fullName,
    required this.price,
    required this.createdAt,
    required this.tags,
    required this.owner,
  });

  final int id;
  final String fullName;
  final double price;
  final DateTime createdAt;
  final List<String> tags;
  final Owner owner;

  factory Root.fromJson(Map<String, dynamic> json) {
    return Root(
      id: json['id'] as int,
      fullName: json['full_name'] as String,
      price: (json['price'] as num).toDouble(),
      createdAt: DateTime.parse(json['created_at'] as String),
      tags: (json['tags'] as List<dynamic>).cast<String>().toList(),
      owner: Owner.fromJson(json['owner'] as Map<String, dynamic>),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'full_name': fullName,
      'price': price,
      'created_at': createdAt.toIso8601String(),
      'tags': tags,
      'owner': owner.toJson(),
    };
  }
}

How JSON values map to Dart types

JSON valueDart typefromJson expression
"text"Stringjson['k'] as String
42intjson['k'] as int
3.5 (or mixed 3 / 3.5)double(json['k'] as num).toDouble()
truebooljson['k'] as bool
"2024-05-01T09:30:00Z"DateTimeDateTime.parse(json['k'] as String)
"x" or nullString?json['k'] as String?
{ … }A named classOwner.fromJson(json['k'] as Map<String, dynamic>)
[ { … } ]List<Item>.map((e) => Item.fromJson(…)).toList()
{}Map<String, dynamic>json['k'] as Map<String, dynamic>
null only, mixed typesdynamicjson['k']

Setting up json_serializable

If you choose the json_serializable style, add the packages and run the code generator once (or use watch while developing):

dart pub add json_annotation
dart pub add --dev json_serializable build_runner
dart run build_runner build --delete-conflicting-outputs
  • The part 'root.g.dart'; line must match the file name of your Dart file.
  • Classes that contain other model classes get @JsonSerializable(explicitToJson: true), so nested objects are converted with their own toJson() instead of being left as instances.
  • Fields whose Dart name differs from the JSON key get @JsonKey(name: 'json_key').

Frequently asked questions

How do I use the generated class with an HTTP response?

Import dart:convert, decode the body and pass the map to the factory: final user = User.fromJson(jsonDecode(response.body) as Map<String, dynamic>). To send data back, call jsonEncode(user.toJson()). If the JSON is a top-level array, map each item with fromJson as shown in the generated comment.

Which fields become nullable?

By default a field gets a nullable type (for example String?) when its value is null somewhere in the sample or when the key is missing from some items of an array. All other fields are non-nullable and marked required in the constructor. You can also make every field nullable, which is safer for APIs that may omit keys.

Why are doubles parsed with (value as num).toDouble()?

jsonDecode returns an int for a number written without a decimal point, so a price of 3 arrives as int even if other items have 3.5. Casting with as double would throw, so the generator casts to num and converts with toDouble(), which accepts both.

Plain Dart or json_serializable: which should I pick?

Plain Dart needs no packages or code generation and is easy to read and debug. json_serializable is popular in larger apps: it writes the conversion code for you in a .g.dart file. With that style, add json_annotation to dependencies and json_serializable plus build_runner to dev_dependencies, then run dart run build_runner build.

How are JSON keys converted to Dart field names?

Keys are converted to lowerCamelCase as recommended by Effective Dart, so first_name becomes firstName. The original key is still used inside fromJson and toJson (or in @JsonKey(name: ...)), so the JSON is read and written unchanged. Reserved words such as class or default get a trailing underscore.

What happens with null-only values and mixed types?

If a value is always null, or mixes types such as string and number, the field is typed dynamic because Dart cannot know a more precise type from the sample. Empty objects become Map<String, dynamic>. Replace dynamic with the real type once you know it.

Is my JSON sent to a server?

No. The JSON is parsed and the Dart code is generated by JavaScript running in this page, so nothing is uploaded.

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 TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON to Rust StructTurn JSON into Rust structs with serde derives, rename attributes, Option and Vec types.JSON to Go StructTurn JSON into Go structs with inferred types, nested structs and json tags.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 Python ClassGenerate Python dataclasses, Pydantic models or TypedDicts with type hints from JSON.JSON to Swift StructTurn JSON into Swift Codable structs with CodingKeys, optionals and nested types.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.CSV CleanerClean messy CSV in one click: trim spaces, drop empty rows and columns, fix headers, dedupe.CSV VLOOKUP ToolJoin two CSV or Excel files on a key column like VLOOKUP, with left, inner and full joins.Remove Duplicates in ExcelFind and remove or highlight duplicate rows in XLSX or CSV files by the columns you choose.GeoJSON ViewerView GeoJSON on a map, inspect and edit properties, validate against RFC 7946 and export.GPX ViewerOpen GPX tracks on a map with distance, elevation profile, moving time, speed and splits.JSON Repair ToolFix broken JSON automatically: trailing commas, quotes, comments, truncated data, with a diff.Karnaugh Map SolverSolve 2–6 variable K-maps: click cells or enter minterms to get the minimal SOP or POS with groups.Merge Excel FilesCombine XLSX, XLS and CSV files into one workbook or append all rows into a single sheet.Parquet File ViewerOpen Apache Parquet files in your browser: schema, rows, filters and CSV or JSON export.Query CSV with SQLRun SQL on CSV, Excel, JSON and Parquet files in your browser with DuckDB. Join and export.Online Serial MonitorTalk to Arduino, ESP32 and USB serial devices in your browser: log, send, plot and save.Split Excel FileSplit an Excel sheet into several files by row count or by each value in a column, as ZIP.SQL Create Table GeneratorDefine columns, keys, defaults and indexes; get CREATE TABLE SQL for MySQL, Postgres and more.SQL IN Clause GeneratorTurn a pasted list into a SQL IN ('a','b') clause with quoting, dedupe and 1,000-item chunks.SQL Online CompilerRun SQL queries online on SQLite with sample databases, a result grid, CSV export and .db save.SQL to ER DiagramPaste CREATE TABLE statements and get an entity-relationship diagram with keys and links.
See all 129 Data & File Format Converters →