Dart serde on sealed classes
10:37 27 Jul 2026

To auto implement JSON serialization and deserialization I use json_serializable but now I need to serialize and deserialize a sealed class.

import 'package:json_annotation/json_annotation.dart';
part 'foo_bar.g.dart';

@JsonSerializable()
sealed class FooBar {}

@JsonSerializable()
class Foo extends FooBar {
  final int fooField;

  Foo(this.fooField);

  Map toJson() => _$FooToJson(this);
  factory Foo.fromJson(Map json) => _$FooFromJson(json);
}

@JsonSerializable()
class Bar extends FooBar {
  final String barField;

  Bar(this.barField);

  Map toJson() => _$BarToJson(this);
  factory Bar.fromJson(Map json) => _$BarFromJson(json);
}

My goal is to be able to serialize and deserialize a FooBar without ever implementing the toJson and fromJson methods, like so:

  final original = Foo(0) as FooBar;
  final reconstructed = FooBar.fromJson(original.toJson());

I have skipped the JSON Map to String encoding and decoding which usually is performed but not relevant.

I would rather not have to open a PR on json_serializable but I'm willing to use freezed or whatever, any suggestions?

best-practices json dart serialization deserialization