JSON to Dart class converter

Paste JSON and get Dart model classes with sound null safety and fromJson/toJson, as plain classes, json_serializable or freezed. A key that is missing or null in any array item becomes nullable, and invalid JSON is reported with its line and column.

Updated

Nested classes are named from their keys: orders becomes Order.

Plain needs no packages and no build step. The other two need build_runner.

Applies only when every value of that key looks like 2026-03-14T09:30:00Z.

Dart classes

3 classes, 14 fields

plain Dart, null safe

Dart classes

class User {
  const User({required this.id, required this.firstName, required this.isActive, required this.balance, required this.createdAt, required this.address, required this.tags, required this.orders});

  final int id;
  final String firstName;
  final bool isActive;
  final double balance;
  final DateTime createdAt;
  final Address address;
  final List<String> tags;
  final List<Order> orders;

  factory User.fromJson(Map<String, dynamic> json) => User(
        id: json['id'] as int,
        firstName: json['first_name'] as String,
        isActive: json['is_active'] as bool,
        balance: (json['balance'] as num).toDouble(),
        createdAt: DateTime.parse(json['created_at'] as String),
        address: Address.fromJson(json['address'] as Map<String, dynamic>),
        tags: (json['tags'] as List<dynamic>).map((e) => e as String).toList(),
        orders: (json['orders'] as List<dynamic>).map((e) => Order.fromJson(e as Map<String, dynamic>)).toList(),
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'first_name': firstName,
        'is_active': isActive,
        'balance': balance,
        'created_at': createdAt.toIso8601String(),
        'address': address.toJson(),
        'tags': tags,
        'orders': orders.map((e) => e.toJson()).toList(),
      };
}

class Address {
  const Address({required this.city, required this.pinCode});

  final String city;
  final String pinCode;

  factory Address.fromJson(Map<String, dynamic> json) => Address(
        city: json['city'] as String,
        pinCode: json['pin_code'] as String,
      );

  Map<String, dynamic> toJson() => {
        'city': city,
        'pin_code': pinCode,
      };
}

class Order {
  const Order({required this.orderId, required this.total, this.coupon, this.note});

  final int orderId;
  final double total;
  final String? coupon;
  final String? note;

  factory Order.fromJson(Map<String, dynamic> json) => Order(
        orderId: json['order_id'] as int,
        total: (json['total'] as num).toDouble(),
        coupon: json['coupon'] as String?,
        note: json['note'] as String?,
      );

  Map<String, dynamic> toJson() => {
        'order_id': orderId,
        'total': total,
        'coupon': coupon,
        if (note != null) 'note': note,
      };
}

// Usage:
// import 'dart:convert';
// final data = User.fromJson(jsonDecode(source) as Map<String, dynamic>);
// final text = jsonEncode(data.toJson());
  • Plain classes need no packages. Add equality, copyWith or toString yourself, or switch to freezed to have them generated.
  • Nullable fields (T?): 1 with a key missing from some objects, 1 with null values in some.

How are Dart classes worked out from JSON?

The JSON is parsed once and every object becomes a class. For a list, all items are read together, not just the first: a key absent from some items, or null in some, becomes a nullable field (String? name), and a number that is 3 in one item and 2.5 in another becomes a double. A key that is null everywhere, or a list that is always empty, has no type to learn, so it is left as dynamic and flagged.

Dart's JSON decoder gives you int for 3 and double for 3.5, so a field that is sometimes a whole number needs (json['price'] as num).toDouble(), not as double: the second throws on 3. That cast is written for every double field. Lists are rebuilt with map(...).toList() because jsonDecode returns List<dynamic>, which is not a List<String>.

Names follow Effective Dart: classes in UpperCamelCase, fields in lowerCamelCase, files in lowercase_with_underscores. The original key stays exactly as written in fromJson and toJson, or in @JsonKey(name: ...) for the generated styles, so pin_code becomes pinCode and still round-trips as pin_code. A key that is a Dart reserved word, such as class, becomes classValue.

Plain classes need nothing but the SDK. json_serializable generates fromJson and toJson into a .g.dart part file when you run build_runner, and freezed adds immutability, equality and copyWith on top of that. Both are code generators, so the file you paste here is not complete until the build step has run.

{"a": 1}  and  {"a": 2.5}  in one list  ->  double a
{"a": 1}  and  {}  or  {"a": null}      ->  int? a
list of objects                          ->  List<Item>   via .map(Item.fromJson).toList()

How does each JSON value map to a Dart type?

Type chosen for a JSON value, and the cast used when reading it
JSONDart typeCast in fromJsonNote
"text"Stringas StringISO 8601 text becomes DateTime when that option is on
3 (no decimal point)intas intBecomes double if any value of that key has a decimal
3.5, 1e3double(x as num).toDouble()A double can arrive as an int, so cast through num
true / falseboolas bool
{ ... }a generated classClass.fromJson(x as Map<String, dynamic>)Same name and same fields share one class
[ ... ]List<T>(x as List<dynamic>).map(...).toList()T comes from all items merged
null, or key missingT?as T?Nullable; in json_serializable also includeIfNull: false when missing
null only / [] onlydynamicno castNothing to infer from

How to turn JSON into Dart classes

  1. 1
    Paste the JSONPaste a real API response, or an array with several items so optional keys show up. If it is invalid, the error gives the line and column.
  2. 2
    Name the root class and pick a stylePlain classes need no packages. Choose json_serializable or freezed if the project already uses build_runner.
  3. 3
    Copy the classes into one fileFor the generated styles, save it under the file name shown so the part directives match, then run dart run build_runner build.
  4. 4
    Decode with the example at the endPass the response body through jsonDecode, then into fromJson as shown. Check the dynamic fields and the nullability against your API docs.

Frequently asked questions

How do I make a Dart field nullable when the JSON key is missing?
Declare it as T? and read it with as T?. In a list, a key that is missing from even one object is marked nullable here. With json_serializable a missing key decodes to null for a nullable field, but a missing key for a non-nullable field throws at runtime, which is why inference across all items matters.
Should I use json_serializable or freezed?
Use json_serializable when you only need parsing and are happy to write equality yourself. Use freezed when you also want immutable models, copyWith and value equality, for example as state in Riverpod or Bloc. Freezed uses json_serializable underneath for fromJson, so you need both packages for JSON.
Why does the generated file complain about _$UserFromJson?
That function does not exist until build_runner has produced the .g.dart file. Check the part directive names match the file name, then run dart run build_runner build. Red squiggles before the first build are expected.
Why use as num instead of as double for decimals?
A JSON number such as 1250 has no decimal point, so Dart's decoder returns an int even when the API means a price. as double throws a type error on it. (x as num).toDouble() accepts both.
What does explicitToJson do?
By default json_serializable's toJson puts nested model objects in the map as they are, not as maps. jsonEncode then calls their toJson itself, so encoding works, but code that inspects the map sees objects. Setting explicitToJson: true makes every level a plain Map.
Why are some fields named differently from the JSON keys?
Dart style wants lowerCamelCase, so first_name becomes firstName. The key itself is preserved in fromJson and toJson, or in @JsonKey(name: 'first_name'), so the data still matches the API exactly.

Sources

Related tools

See all 135 free tools

Need a custom dev tool for your team?

We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.

Built by CountryDevs · No signup · No ads · We count visits, never what you enter