Object serialization

suggest change

Serialization turns an object into data you can store or send: a string, a list of bytes, a message to another isolate. Deserialization builds an object back from that data.

Dart has no built-in reflection-based serializer. dart:mirrors isn't available in Flutter or AOT-compiled programs, so there's no Serializable interface and no way to dump an arbitrary object. Instead, the convention is that a class converts itself to and from plain data: maps, lists, strings, numbers, booleans and null. Those values map directly onto JSON, and from there onto YAML, MessagePack, databases and other formats.

This article covers:

The examples were run with Dart 3.13, json_serializable 6.14 and json_annotation 4.12.

For the formats themselves, see JSON, YAML, Protocol Buffers (a schema-first alternative that generates the classes for you) and Bytes and binary data (writing your own binary format).

toJson and fromJson

The convention has two parts:

jsonEncode knows the convention. When it meets an object that isn't a number, string, bool, null, list or map, it calls the object's toJson() method and encodes whatever comes back:

import 'dart:convert';

class User {
  final int id;
  final String name;
  final String? email;

  User({required this.id, required this.name, this.email});

  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json['id'] as int,
    name: json['name'] as String,
    email: json['email'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'id': id,
    'name': name,
    if (email != null) 'email': email,
  };

  @override
  String toString() => 'User($id, $name, $email)';
}

void main() {
  final user = User(id: 1, name: 'Ann', email: 'ann@example.com');

  // jsonEncode calls toJson() on objects it doesn't know how to encode
  final text = jsonEncode(user);
  print(text);

  final back = User.fromJson(jsonDecode(text) as Map<String, dynamic>);
  print(back);

  // lists of objects work too
  final users = [user, User(id: 2, name: 'Bob')];
  print(jsonEncode(users));

  final decoded = (jsonDecode(jsonEncode(users)) as List)
      .map((e) => User.fromJson(e as Map<String, dynamic>))
      .toList();
  print(decoded);

  // pretty printing
  print(const JsonEncoder.withIndent('  ').convert(user));
}

Output:

{"id":1,"name":"Ann","email":"ann@example.com"}
User(1, Ann, ann@example.com)
[{"id":1,"name":"Ann","email":"ann@example.com"},{"id":2,"name":"Bob"}]
[User(1, Ann, ann@example.com), User(2, Bob, null)]
{
  "id": 1,
  "name": "Ann",
  "email": "ann@example.com"
}

Some details:

Nested objects, enums and dates

JSON has no dates, enums or typed lists, so toJson converts them to strings, numbers and maps and fromJson converts them back:

import 'dart:convert';

enum Status { pending, paid, shipped }

class LineItem {
  final String sku;
  final int quantity;
  final double price;

  LineItem(this.sku, this.quantity, this.price);

  factory LineItem.fromJson(Map<String, dynamic> json) => LineItem(
    json['sku'] as String,
    json['quantity'] as int,
    (json['price'] as num).toDouble(), // 5 decodes as int, 5.5 as double
  );

  Map<String, dynamic> toJson() => {
    'sku': sku,
    'quantity': quantity,
    'price': price,
  };
}

class Order {
  final String id;
  final DateTime created;
  final Status status;
  final List<LineItem> items;
  final Map<String, String> tags;

  Order(this.id, this.created, this.status, this.items, this.tags);

  factory Order.fromJson(Map<String, dynamic> json) => Order(
    json['id'] as String,
    DateTime.parse(json['created'] as String),
    Status.values.byName(json['status'] as String),
    [
      for (final e in json['items'] as List)
        LineItem.fromJson(e as Map<String, dynamic>),
    ],
    (json['tags'] as Map<String, dynamic>).cast<String, String>(),
  );

  Map<String, dynamic> toJson() => {
    'id': id,
    'created': created.toUtc().toIso8601String(),
    'status': status.name,
    'items': [for (final i in items) i.toJson()],
    'tags': tags,
  };

  double get total => items.fold(0, (s, i) => s + i.quantity * i.price);
}

void main() {
  final order = Order(
    'A-100',
    DateTime.utc(2026, 10, 17, 9, 30),
    Status.paid,
    [LineItem('pen', 3, 1.5), LineItem('book', 1, 20)],
    {'channel': 'web'},
  );

  final text = jsonEncode(order);
  print(text);

  final back = Order.fromJson(jsonDecode(text));
  print('${back.id} ${back.created} ${back.status} total=${back.total}');
  print(back.items[1].price.runtimeType);
}

Output:

{"id":"A-100","created":"2026-10-17T09:30:00.000Z","status":"paid","items":[{"sku":"pen","quantity":3,"price":1.5},{"sku":"book","quantity":1,"price":20.0}],"tags":{"channel":"web"}}
A-100 2026-10-17 09:30:00.000Z Status.paid total=24.5
double

Things that commonly go wrong here:

Objects without toJson

If an object has no toJson method, jsonEncode throws a JsonUnsupportedObjectError. For types you don't control, such as DateTime, Set or a class from another package, pass a toEncodable function. It's called for every value the encoder can't handle:

import 'dart:convert';

class Point {
  final int x, y;
  Point(this.x, this.y);
}

void main() {
  try {
    jsonEncode({'p': Point(1, 2)});
  } on JsonUnsupportedObjectError catch (e) {
    print(e);
    print('cause: ${e.cause}');
  }

  // toEncodable is called for every object jsonEncode can't handle
  final text = jsonEncode(
    {
      'p': Point(1, 2),
      'when': DateTime.utc(2026, 1, 2),
      'tags': {'a', 'b'},
    },
    toEncodable: (Object? o) => switch (o) {
      Point(:final x, :final y) => [x, y],
      DateTime d => d.toIso8601String(),
      Set s => s.toList(),
      _ => throw UnsupportedError('cannot encode ${o.runtimeType}'),
    },
  );
  print(text);
}

Output:

Converting object to an encodable object failed: Instance of 'Point'
cause: NoSuchMethodError: Class 'Point' has no instance method 'toJson'.
Receiver: Instance of 'Point'
Tried calling: toJson()
{"p":[1,2],"when":"2026-01-02T00:00:00.000Z","tags":["a","b"]}

toEncodable only works in one direction. When you decode, nothing tells you that [1, 2] was a Point, so for your own classes toJson/fromJson is the better choice.

Validating input with patterns

Casts such as json['id'] as int throw a TypeError when the data has the wrong shape. That's fine for data your own program wrote. For data from a network or a file a user can edit, you want a clear FormatException that you can catch and report. Dart 3 map patterns check the keys and the types in one step:

import 'dart:convert';

class User {
  final int id;
  final String name;
  final String? email;

  User({required this.id, required this.name, this.email});

  factory User.fromJsonUnchecked(Map<String, dynamic> json) => User(
    id: json['id'] as int,
    name: json['name'] as String,
    email: json['email'] as String?,
  );

  factory User.fromJson(Object? json) {
    return switch (json) {
      {'id': int id, 'name': String name, 'email': String? email} => User(
        id: id,
        name: name,
        email: email,
      ),
      {'id': int id, 'name': String name} => User(id: id, name: name),
      _ => throw FormatException('invalid user', json),
    };
  }

  @override
  String toString() => 'User($id, $name, $email)';
}

void main() {
  const inputs = [
    '{"id": 1, "name": "Ann", "email": "ann@example.com"}',
    '{"id": 2, "name": "Bob"}',
    '{"id": "3", "name": "Cy"}',
    '[1, 2]',
  ];

  for (final input in inputs) {
    final json = jsonDecode(input);
    try {
      print(User.fromJson(json));
    } on FormatException catch (e) {
      print('${e.message}: ${e.source}');
    }
  }

  try {
    User.fromJsonUnchecked(jsonDecode(inputs[2]));
  } on TypeError catch (e) {
    print('TypeError: $e');
  }
}

Output:

User(1, Ann, ann@example.com)
User(2, Bob, null)
invalid user: {id: 3, name: Cy}
invalid user: [1, 2]
TypeError: type 'String' is not a subtype of type 'int' in type cast

A map pattern only matches when every listed key is present, so the optional email needs a second case. The first case matches both "email": "..." and "email": null. Because fromJson takes Object?, it also rejects input that isn't a map at all. See Pattern matching for more on patterns.

Generating the code with json_serializable

Hand-written toJson/fromJson gets tedious and error-prone once you have dozens of classes, and it's easy to add a field and forget to serialize it. json_serializable generates both methods from annotations. Add the packages:

dart pub add json_annotation
dart pub add dev:build_runner dev:json_serializable

Annotate the class, add a part directive for the generated file, and forward fromJson/toJson to the generated functions:

// lib/models.dart
import 'package:json_annotation/json_annotation.dart';

part 'models.g.dart';

enum Role {
  @JsonValue('admin')
  administrator,
  editor,
  viewer,
}

@JsonSerializable(explicitToJson: true, fieldRename: FieldRename.snake)
class Account {
  final int id;
  final String displayName;
  final Role role;
  final DateTime createdAt;
  final Address? address;

  @JsonKey(defaultValue: <String>[])
  final List<String> tags;

  @JsonKey(includeIfNull: false)
  final String? avatarUrl;

  @JsonKey(includeFromJson: false, includeToJson: false)
  int loginCount = 0;

  Account({
    required this.id,
    required this.displayName,
    required this.role,
    required this.createdAt,
    this.address,
    this.tags = const [],
    this.avatarUrl,
  });

  factory Account.fromJson(Map<String, dynamic> json) =>
      _$AccountFromJson(json);

  Map<String, dynamic> toJson() => _$AccountToJson(this);
}

@JsonSerializable()
class Address {
  final String city;
  @JsonKey(name: 'zip')
  final String postalCode;

  Address(this.city, this.postalCode);

  factory Address.fromJson(Map<String, dynamic> json) =>
      _$AddressFromJson(json);

  Map<String, dynamic> toJson() => _$AddressToJson(this);
}

Generate models.g.dart, once or continuously while you edit:

dart run build_runner build
dart run build_runner watch

Using the classes:

import 'dart:convert';

import 'package:ser/models.dart';

void main() {
  final account = Account(
    id: 7,
    displayName: 'Ann Lee',
    role: Role.administrator,
    createdAt: DateTime.utc(2026, 10, 17),
    address: Address('Oslo', '0150'),
    tags: ['beta'],
  );

  final text = jsonEncode(account);
  print(text);

  final back = Account.fromJson(jsonDecode(text));
  print('${back.displayName} ${back.role} ${back.address!.city}');

  // tags is missing: defaultValue kicks in
  final minimal = Account.fromJson({
    'id': 8,
    'display_name': 'Bob',
    'role': 'viewer',
    'created_at': '2026-01-01T00:00:00Z',
  });
  print('${minimal.tags} ${minimal.address} ${minimal.avatarUrl}');
}

Output:

{"id":7,"display_name":"Ann Lee","role":"admin","created_at":"2026-10-17T00:00:00.000Z","address":{"city":"Oslo","zip":"0150"},"tags":["beta"]}
Ann Lee Role.administrator Oslo
[] null null

The generated code is ordinary Dart, much like what you'd write by hand. It's worth reading when something doesn't behave the way you expect:

Account _$AccountFromJson(Map<String, dynamic> json) => Account(
  id: (json['id'] as num).toInt(),
  displayName: json['display_name'] as String,
  role: $enumDecode(_$RoleEnumMap, json['role']),
  createdAt: DateTime.parse(json['created_at'] as String),
  address: json['address'] == null
      ? null
      : Address.fromJson(json['address'] as Map<String, dynamic>),
  tags:
      (json['tags'] as List<dynamic>?)?.map((e) => e as String).toList() ?? [],
  avatarUrl: json['avatar_url'] as String?,
);

Map<String, dynamic> _$AccountToJson(Account instance) => <String, dynamic>{
  'id': instance.id,
  'display_name': instance.displayName,
  'role': _$RoleEnumMap[instance.role]!,
  'created_at': instance.createdAt.toIso8601String(),
  'address': instance.address?.toJson(),
  'tags': instance.tags,
  'avatar_url': ?instance.avatarUrl,
};

What the annotations do:

Annotation Effect
fieldRename: FieldRename.snake displayName is stored as display_name (also kebab, pascal, screamingSnake)
@JsonKey(name: 'zip') a specific key for one field
@JsonKey(defaultValue: ...) the value to use when the key is missing or null
@JsonKey(includeIfNull: false) omit the key when the value is null
@JsonKey(includeFromJson: false, includeToJson: false) don't serialize the field at all
@JsonValue('admin') the stored string for an enum value
explicitToJson: true call toJson() on nested objects inside toJson

explicitToJson deserves a note. Without it the generated code writes 'address': instance.address, so the map returned by toJson() contains an Address object, not a map. jsonEncode still works because it calls toJson on the nested object later. But anything else that expects plain data, like a YAML writer, a database driver or a deep equality check in a test, breaks. Turn it on everywhere.

Instead of repeating options on each class, set them for the whole package in build.yaml next to pubspec.yaml:

targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true
          field_rename: snake
          include_if_null: false

Custom converters and strict parsing

For a type json_serializable doesn't support, or one you want stored differently, write a JsonConverter. Putting the converter on the class applies it to every field of that type. checked: true makes errors report which key failed, disallowUnrecognizedKeys rejects unexpected keys, and unknownEnumValue is a fallback for enum values added by a newer version of the producer:

// lib/event.dart
import 'package:json_annotation/json_annotation.dart';

part 'event.g.dart';

/// Stores a Duration as whole seconds.
class SecondsConverter implements JsonConverter<Duration, int> {
  const SecondsConverter();

  @override
  Duration fromJson(int json) => Duration(seconds: json);

  @override
  int toJson(Duration object) => object.inSeconds;
}

/// Stores a DateTime as Unix epoch milliseconds.
class EpochConverter implements JsonConverter<DateTime, int> {
  const EpochConverter();

  @override
  DateTime fromJson(int json) =>
      DateTime.fromMillisecondsSinceEpoch(json, isUtc: true);

  @override
  int toJson(DateTime object) => object.millisecondsSinceEpoch;
}

enum Priority { low, normal, high, unknown }

@JsonSerializable(checked: true, disallowUnrecognizedKeys: true)
@SecondsConverter()
@EpochConverter()
class Event {
  final String title;
  final DateTime start;
  final Duration length;

  @JsonKey(unknownEnumValue: Priority.unknown)
  final Priority priority;

  Event(this.title, this.start, this.length, this.priority);

  factory Event.fromJson(Map<String, dynamic> json) => _$EventFromJson(json);

  Map<String, dynamic> toJson() => _$EventToJson(this);
}
import 'dart:convert';

import 'package:json_annotation/json_annotation.dart';
import 'package:ser/event.dart';

void main() {
  final e = Event(
    'standup',
    DateTime.utc(2026, 10, 19, 9),
    Duration(minutes: 15),
    Priority.normal,
  );
  final text = jsonEncode(e);
  print(text);

  final fromNewerApp = Event.fromJson(
    jsonDecode('{"title":"x","start":0,"length":60,"priority":"urgent"}'),
  );
  print(
    '${fromNewerApp.start} ${fromNewerApp.length} ${fromNewerApp.priority}',
  );

  const bad = [
    '{"title":"x","start":"monday","length":60,"priority":"low"}',
    '{"title":"x","start":0,"length":60,"priority":"low","color":"red"}',
  ];
  for (final input in bad) {
    try {
      Event.fromJson(jsonDecode(input));
    } on CheckedFromJsonException catch (ex) {
      print('${ex.className} key=${ex.key}: ${ex.message}');
    }
  }
}

Output:

{"title":"standup","start":1792400400000,"length":900,"priority":"normal"}
1970-01-01 00:00:00.000Z 0:01:00.000000 Priority.unknown
Event key=start: type 'String' is not a subtype of type 'num' in type cast
Event key=null: Unrecognized keys: [color]; supported keys: [title, start, length, priority]

If you also want immutable classes with copyWith and value equality, freezed generates those and uses json_serializable for the JSON part. See Immutability.

Polymorphic types with sealed classes

A field of type Shape can hold a Circle, a Rect or a Group. JSON doesn't record the class, so you add a discriminator field, usually "type", and the base class's fromJson picks the subclass from it. A sealed base class works well for this. The compiler knows every subclass, so a switch over a Shape must handle all of them, and adding a new shape points you at every place that needs updating:

import 'dart:convert';
import 'dart:math';

sealed class Shape {
  const Shape();

  factory Shape.fromJson(Map<String, dynamic> json) => switch (json) {
    {'type': 'circle', 'radius': num r} => Circle(r.toDouble()),
    {'type': 'rect', 'width': num w, 'height': num h} => Rect(
      w.toDouble(),
      h.toDouble(),
    ),
    {'type': 'group', 'children': List children} => Group([
      for (final c in children) Shape.fromJson(c as Map<String, dynamic>),
    ]),
    {'type': String t} => throw FormatException('unknown shape type "$t"'),
    _ => throw FormatException('missing "type"', json),
  };

  Map<String, dynamic> toJson();
}

class Circle extends Shape {
  final double radius;
  const Circle(this.radius);

  @override
  Map<String, dynamic> toJson() => {'type': 'circle', 'radius': radius};
}

class Rect extends Shape {
  final double width, height;
  const Rect(this.width, this.height);

  @override
  Map<String, dynamic> toJson() => {
    'type': 'rect',
    'width': width,
    'height': height,
  };
}

class Group extends Shape {
  final List<Shape> children;
  const Group(this.children);

  @override
  Map<String, dynamic> toJson() => {
    'type': 'group',
    'children': [for (final c in children) c.toJson()],
  };
}

// exhaustive: adding a new subclass makes this a compile error
double area(Shape s) => switch (s) {
  Circle(:final radius) => pi * radius * radius,
  Rect(:final width, :final height) => width * height,
  Group(:final children) => children.fold(0, (sum, c) => sum + area(c)),
};

void main() {
  final drawing = Group([
    Circle(1),
    Rect(2, 3),
    Group([Rect(1, 1)]),
  ]);
  final text = jsonEncode(drawing);
  print(text);

  final back = Shape.fromJson(jsonDecode(text));
  print(back.runtimeType);
  print(area(back).toStringAsFixed(2));

  try {
    Shape.fromJson({'type': 'triangle'});
  } on FormatException catch (e) {
    print(e.message);
  }
}

Output:

{"type":"group","children":[{"type":"circle","radius":1.0},{"type":"rect","width":2.0,"height":3.0},{"type":"group","children":[{"type":"rect","width":1.0,"height":1.0}]}]}
Group
10.14
unknown shape type "triangle"

Use a stable string such as 'circle' as the discriminator, not runtimeType.toString(). Class names change when you refactor, and they get minified in web builds.

Sealed classes with json_serializable

json_serializable generates the code for each subclass but doesn't dispatch on a type field by itself. Keep the switch in the base class and add the discriminator in each subclass's toJson:

// lib/message.dart
import 'package:json_annotation/json_annotation.dart';

part 'message.g.dart';

sealed class Message {
  const Message();

  factory Message.fromJson(Map<String, dynamic> json) => switch (json['type']) {
    'text' => TextMessage.fromJson(json),
    'image' => ImageMessage.fromJson(json),
    final t => throw FormatException('unknown message type: $t'),
  };

  Map<String, dynamic> toJson();
}

@JsonSerializable()
class TextMessage extends Message {
  final String body;
  const TextMessage(this.body);

  factory TextMessage.fromJson(Map<String, dynamic> json) =>
      _$TextMessageFromJson(json);

  @override
  Map<String, dynamic> toJson() => {
    'type': 'text',
    ..._$TextMessageToJson(this),
  };
}

@JsonSerializable()
class ImageMessage extends Message {
  final Uri url;
  final int width, height;
  const ImageMessage(this.url, this.width, this.height);

  factory ImageMessage.fromJson(Map<String, dynamic> json) =>
      _$ImageMessageFromJson(json);

  @override
  Map<String, dynamic> toJson() => {
    'type': 'image',
    ..._$ImageMessageToJson(this),
  };
}

@JsonSerializable(explicitToJson: true)
class Conversation {
  final String id;
  final List<Message> messages;
  Conversation(this.id, this.messages);

  factory Conversation.fromJson(Map<String, dynamic> json) =>
      _$ConversationFromJson(json);

  Map<String, dynamic> toJson() => _$ConversationToJson(this);
}

Conversation has a List<Message> field. The generator sees that Message has a fromJson constructor and a toJson method and uses them, so the polymorphism works through nested fields:

import 'dart:convert';

import 'package:ser/message.dart';

void main() {
  final conv = Conversation('c1', [
    TextMessage('look at this'),
    ImageMessage(Uri.parse('https://example.com/cat.png'), 640, 480),
  ]);
  final text = jsonEncode(conv);
  print(text);

  final back = Conversation.fromJson(jsonDecode(text));
  for (final m in back.messages) {
    print(switch (m) {
      TextMessage(:final body) => 'text: $body',
      ImageMessage(:final url, :final width) => 'image: ${url.host} ${width}px',
    });
  }
}

Output:

{"id":"c1","messages":[{"type":"text","body":"look at this"},{"type":"image","url":"https://example.com/cat.png","width":640,"height":480}]}
text: look at this
image: example.com 640px

freezed can generate this dispatch for you with @Freezed(unionKey: 'type') and @FreezedUnionValue('text').

Versioning

Serialized data outlives the code that wrote it. Settings files, cached responses and database documents written by version 1 of your app will be read by version 5. Plan for that from the start:

A simple migration scheme: write "version" with every object, and when reading, upgrade the raw map one version at a time before parsing it:

import 'dart:convert';

class Settings {
  static const currentVersion = 3;

  final bool darkMode;
  final int fontSize;
  final String language;

  Settings({
    required this.darkMode,
    required this.fontSize,
    this.language = 'en',
  });

  Map<String, dynamic> toJson() => {
    'version': currentVersion,
    'dark_mode': darkMode,
    'font_size': fontSize,
    'language': language,
  };

  factory Settings.fromJson(Map<String, dynamic> json) {
    final version = json['version'] as int? ?? 1; // v1 files had no version
    if (version > currentVersion) {
      throw FormatException(
        'settings version $version is newer than '
        'this app supports ($currentVersion)',
      );
    }
    var data = Map<String, dynamic>.of(json);
    for (var v = version; v < currentVersion; v++) {
      data = _migrations[v]!(data);
    }
    return Settings(
      darkMode: data['dark_mode'] as bool,
      fontSize: (data['font_size'] as num).toInt(),
      language: data['language'] as String? ?? 'en',
    );
  }

  // _migrations[n] upgrades a version n map to version n + 1
  static final _migrations =
      <int, Map<String, dynamic> Function(Map<String, dynamic>)>{
        // v1 -> v2: "theme": "dark"|"light" became the boolean "dark_mode"
        1: (m) => m..['dark_mode'] = m.remove('theme') == 'dark',
        // v2 -> v3: "fontSize" was renamed to "font_size"
        2: (m) => m..['font_size'] = m.remove('fontSize') ?? 14,
      };

  @override
  String toString() =>
      'Settings(dark=$darkMode, font=$fontSize, lang=$language)';
}

void main() {
  const stored = [
    '{"theme": "dark", "fontSize": 12}',
    '{"version": 2, "dark_mode": false, "fontSize": 16, "language": "pl"}',
    '{"version": 3, "dark_mode": true, "font_size": 18, "language": "de"}',
    '{"version": 4, "dark_mode": true, "font_size": 18}',
  ];
  for (final s in stored) {
    try {
      final settings = Settings.fromJson(jsonDecode(s));
      print('$settings -> ${jsonEncode(settings)}');
    } on FormatException catch (e) {
      print(e.message);
    }
  }
}

Output:

Settings(dark=true, font=12, lang=en) -> {"version":3,"dark_mode":true,"font_size":12,"language":"en"}
Settings(dark=false, font=16, lang=pl) -> {"version":3,"dark_mode":false,"font_size":16,"language":"pl"}
Settings(dark=true, font=18, lang=de) -> {"version":3,"dark_mode":true,"font_size":18,"language":"de"}
settings version 4 is newer than this app supports (3)

Each migration only knows about two adjacent versions, so supporting a new version means adding one function. The migrations work on maps, so they also fit in front of a generated _$SettingsFromJson. Data from a newer version is rejected, not guessed at.

Keeping fields you don't know about

There's a subtler problem when an older version of the app reads data written by a newer one, edits it and saves it back. Fields the old version doesn't know about get dropped. If several app versions share the same data, such as a synced document or a config file edited by two tools, keep unknown keys and write them back:

import 'dart:convert';

class Profile {
  final String name;
  final int age;
  final Map<String, dynamic> _unknown; // fields written by newer versions

  Profile(this.name, this.age, [this._unknown = const {}]);

  static const _known = {'name', 'age'};

  factory Profile.fromJson(Map<String, dynamic> json) =>
      Profile(json['name'] as String, json['age'] as int, {
        for (final MapEntry(:key, :value) in json.entries)
          if (!_known.contains(key)) key: value,
      });

  Map<String, dynamic> toJson() => {..._unknown, 'name': name, 'age': age};

  Profile withAge(int age) => Profile(name, age, _unknown);
}

void main() {
  // written by v2 of the app, which added "nickname"
  const fromV2 = '{"name":"Ann","age":30,"nickname":"annie"}';

  // v1 reads it, changes the age and saves it back
  final p = Profile.fromJson(jsonDecode(fromV2)).withAge(31);
  print(jsonEncode(p));
}

Output:

{"nickname":"annie","name":"Ann","age":31}

Protocol Buffers do this automatically and have well-defined rules for evolving a schema. If versioning is central to your data, see Protocol Buffers.

Isolates: no serialization needed

When you send an object to another isolate of the same program, with Isolate.run, SendPort.send or Isolate.exit, Dart copies the object graph directly. Your class needs no toJson, and the receiver gets an instance of the same class. The copy is deep, so changes on one side are invisible to the other:

import 'dart:convert';
import 'dart:isolate';

class User {
  final int id;
  final String name;
  final List<String> roles;
  User(this.id, this.name, this.roles);

  factory User.fromJson(Map<String, dynamic> json) => User(
    json['id'] as int,
    json['name'] as String,
    (json['roles'] as List).cast<String>(),
  );

  Map<String, dynamic> toJson() => {'id': id, 'name': name, 'roles': roles};
}

class Job {
  final String name;
  final replies = ReceivePort(); // can't be copied to another isolate
  Job(this.name);
}

Future<void> main() async {
  // 1. Objects are copied between isolates of the same program: no toJson needed
  final ann = User(1, 'Ann', ['admin']);
  final copy = await Isolate.run(() {
    ann.roles.add('changed in worker'); // mutates the worker's copy
    return ann;
  });
  print('${copy.name} ${copy.roles} identical=${identical(ann, copy)}');
  print('original: ${ann.roles}');

  // 2. Decode a large JSON payload off the main isolate, get typed objects back
  final payload = jsonEncode([
    for (var i = 0; i < 100000; i++) User(i, 'user$i', ['viewer']),
  ]);
  print('payload: ${payload.length} chars');
  final users = await Isolate.run(
    () => [
      for (final e in jsonDecode(payload) as List)
        User.fromJson(e as Map<String, dynamic>),
    ],
  );
  print('decoded ${users.length} users, last=${users.last.name}');

  // 3. Some objects can't cross an isolate boundary
  final job = Job('report');
  try {
    await Isolate.run(() => job.name);
  } on ArgumentError catch (e) {
    print((e.message as String).split('\n').first);
  }

  // pass only the data the worker needs, from a separate function
  print(await shout(job.name));
  job.replies.close();
}

// the closure can only capture this function's variables
Future<String> shout(String name) => Isolate.run(() => name.toUpperCase());

Output:

Ann [admin, changed in worker] identical=false
original: [admin]
payload: 5077781 chars
decoded 100000 users, last=user99999
Illegal argument in isolate message: object is unsendable - Library:'dart:isolate' Class: _ReceivePortImpl@1026248 (see restrictions listed at `SendPort.send()` documentation for more information)
REPORT

Things to know:

Summary

Task Code
Object to map Map<String, dynamic> toJson() => {'id': id, ...}
Map to object factory User.fromJson(Map<String, dynamic> json) => User(...)
Object to JSON text jsonEncode(obj) calls obj.toJson()
JSON text to object User.fromJson(jsonDecode(text))
List of objects [for (final e in json['items'] as List) Item.fromJson(e)]
Numbers (json['price'] as num).toDouble()
Enums status.name and Status.values.byName(s)
Dates d.toUtc().toIso8601String() and DateTime.parse(s)
Types without toJson jsonEncode(obj, toEncodable: (o) => ...)
Validate input switch (json) { {'id': int id} => ..., _ => throw FormatException(...) }
Generate code @JsonSerializable(), part 'x.g.dart', dart run build_runner build
Polymorphism "type" field and a switch in a sealed class's fromJson
Versioning write "version", migrate the map step by step before parsing
Objects to an isolate send them directly, no serialization
Decode off the main thread await Isolate.run(() => User.fromJson(jsonDecode(text)))

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents