JSON to Dart
Generate Dart classes from JSON with fromJson and toJson
JSON Input
Dart Output
What is JSON to Dart Conversion?
JSON to Dart conversion takes a raw JSON object and produces Dart class definitions with typed fields, a named constructor, a fromJson factory, and a toJson method. Dart has no runtime reflection in Flutter (dart:mirrors is disabled), so you cannot deserialize JSON into typed objects without writing explicit mapping code. Every REST API response, Firebase document, or config payload needs a corresponding Dart model class before you can access its fields with type safety.
A typical Dart model class for JSON declares final fields for each key, a constructor with named parameters (using the required keyword for non-nullable fields), a factory constructor named fromJson that reads from a Map of String to dynamic, and a toJson method that returns a Map of String to dynamic. Nested JSON objects become separate classes. Arrays become typed List fields. Nullable JSON values use Dart's null-safety syntax with the ? suffix on the type.
Writing these model classes by hand means reading each JSON key, deciding the Dart type, creating the fromJson cast for each field (including list mapping with .map().toList()), building a toJson map literal, and repeating for every nested object. For a JSON object with 12 fields and 2 nested objects, that means 3 classes, 6 factory lines, and dozens of cast expressions. A converter produces all of this in milliseconds from a single paste.
Why Use a JSON to Dart Converter?
Manually writing Dart model classes from JSON involves reading field names, guessing types from sample values, writing fromJson casts with correct null handling, and repeating the process for nested objects. When the API shape changes, every field update touches the constructor, fromJson, and toJson. A converter removes that repetitive work.
JSON to Dart Use Cases
JSON to Dart Type Mapping
Every JSON value maps to a specific Dart type. The table below shows how the converter translates each JSON type. The Alternative column shows types used in less common or manual mapping scenarios.
| JSON Type | Example | Dart Type | Alternative |
|---|---|---|---|
| string | "hello" | String | String |
| number (integer) | 42 | int | int |
| number (float) | 3.14 | double | double |
| boolean | true | bool | bool |
| null | null | dynamic | Null / dynamic |
| object | {"k": "v"} | NestedClass | Map<String, dynamic> |
| array of strings | ["a", "b"] | List<String> | List<String> |
| array of objects | [{"id": 1}] | List<Item> | List<Item> |
| mixed array | [1, "a"] | List<dynamic> | List<dynamic> |
Dart JSON Serialization Approaches
Dart and Flutter offer multiple ways to handle JSON serialization. Manual fromJson/toJson is the simplest approach and requires no code generation. For larger projects, build_runner-based solutions like json_serializable and freezed generate the boilerplate at compile time, reducing errors and keeping models consistent with the JSON contract.
| Approach | Description | Source |
|---|---|---|
| json_serializable | Code-generation-based JSON serialization. Generates .g.dart files at build time via build_runner. Type-safe and compile-time verified. | Official (Google) |
| freezed | Generates immutable data classes with copyWith, fromJson/toJson, equality, and pattern matching support. Built on top of json_serializable. | Community (rrousselGit) |
| built_value | Generates immutable value types with serialization. Enforces immutability patterns. Used in larger codebases with strict data modeling. | |
| dart_mappable | Annotation-based mapper that generates fromJson, toJson, copyWith, and equality. Simpler setup than freezed with similar features. | Community |
| Manual fromJson/toJson | Hand-written factory constructors and toJson methods. No code generation needed. Full control over the mapping logic. | Built-in Dart |
Manual vs json_serializable vs freezed
Dart has three common approaches for JSON model classes. Manual fromJson/toJson has zero dependencies. json_serializable automates the mapping code. freezed adds immutability, copyWith, and pattern matching on top of json_serializable.
Code Examples
These examples show how to use generated Dart classes for JSON deserialization, how to set up json_serializable with build_runner, and how to generate Dart classes programmatically from JavaScript and Python.
import 'dart:convert';
class User {
final int id;
final String name;
final String email;
final bool active;
final Address address;
final List<String> tags;
User({
required this.id,
required this.name,
required this.email,
required this.active,
required this.address,
required this.tags,
});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json['id'] as int,
name: json['name'] as String,
email: json['email'] as String,
active: json['active'] as bool,
address: Address.fromJson(json['address'] as Map<String, dynamic>),
tags: (json['tags'] as List<dynamic>).map((e) => e as String).toList(),
);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'email': email,
'active': active,
'address': address.toJson(),
'tags': tags,
};
}
class Address {
final String street;
final String city;
final String zip;
Address({required this.street, required this.city, required this.zip});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json['street'] as String,
city: json['city'] as String,
zip: json['zip'] as String,
);
Map<String, dynamic> toJson() => {'street': street, 'city': city, 'zip': zip};
}
void main() {
final jsonStr = '{"id":1,"name":"Alice","email":"alice@example.com","active":true,"address":{"street":"123 Main","city":"Springfield","zip":"12345"},"tags":["admin","user"]}';
final user = User.fromJson(jsonDecode(jsonStr));
print(user.name); // -> Alice
print(jsonEncode(user.toJson())); // -> round-trip back to JSON
}// pubspec.yaml dependencies:
// json_annotation: ^4.8.0
// dev_dependencies:
// build_runner: ^2.4.0
// json_serializable: ^6.7.0
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart'; // generated by: dart run build_runner build
@JsonSerializable()
class User {
final int id;
final String name;
final String email;
@JsonKey(name: 'is_active')
final bool isActive;
final List<String> tags;
User({
required this.id,
required this.name,
required this.email,
required this.isActive,
required this.tags,
});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
// Run code generation:
// dart run build_runner build --delete-conflicting-outputsfunction jsonToDart(obj, name = "Root") {
const classes = [];
function infer(val, fieldName) {
if (val === null) return "dynamic";
if (typeof val === "string") return "String";
if (typeof val === "number") return Number.isInteger(val) ? "int" : "double";
if (typeof val === "boolean") return "bool";
if (Array.isArray(val)) {
const first = val.find(v => v !== null);
if (!first) return "List<dynamic>";
return `List<${infer(first, fieldName)}>`;
}
if (typeof val === "object") {
const cls = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
build(val, cls);
return cls;
}
return "dynamic";
}
function build(obj, cls) {
const fields = Object.entries(obj).map(([k, v]) =>
` final ${infer(v, k)} ${k};`
);
classes.push(`class ${cls} {\n${fields.join("\n")}\n}`);
}
build(obj, name);
return classes.join("\n\n");
}
console.log(jsonToDart({ id: 1, name: "Alice", scores: [98, 85] }, "User"));
// class User {
// final int id;
// final String name;
// final List<int> scores;
// }import json
def json_to_dart(obj: dict, class_name: str = "Root") -> str:
classes = []
def infer(val, name):
if val is None:
return "dynamic"
if isinstance(val, bool):
return "bool"
if isinstance(val, int):
return "int"
if isinstance(val, float):
return "double"
if isinstance(val, str):
return "String"
if isinstance(val, list):
if not val:
return "List<dynamic>"
return f"List<{infer(val[0], name)}>"
if isinstance(val, dict):
cls = name[0].upper() + name[1:]
build(val, cls)
return cls
return "dynamic"
def build(obj, cls):
fields = [f" final {infer(v, k)} {k};" for k, v in obj.items()]
classes.append(f"class {cls} {{\n" + "\n".join(fields) + "\n}")
build(obj, class_name)
return "\n\n".join(classes)
data = json.loads('{"id": 1, "name": "Alice", "active": true}')
print(json_to_dart(data, "User"))
# class User {
# final int id;
# final String name;
# final bool active;
# }