8. Networking & Serialization

JSON Serialization & Data Models

Master serialization in Flutter without reflection: manual fromJson/toJson contracts, automated json_serializable code-gen, and immutable value objects with Freezed.

1. Why Flutter Disables Reflection (dart:mirrors)

In backend Java (Jackson) or C# (Newtonsoft), JSON parsers inspect object fields dynamically at runtime via reflection.

In Flutter, reflection (dart:mirrors) is disabled by design:

  • Tree Shaking & Binary Size: Ahead-Of-Time (AOT) compilers can aggressively strip unused code only when field access is statically known at compile time.
  • Startup Velocity: Dynamic reflection incurs runtime lookup overhead that degrades app boot time.

Consequently, Dart serialization relies on explicit serialization methods or compile-time code generation.

1. Parse String 2. Produces Map 3. User.fromJson(map) Raw JSON String: '{\"id\": 1, \"name\": \"Alex\"}' jsonDecode() (dart:convert) Map<String, dynamic> Typed Dart Model: User(id: 1, name: 'Alex')

2. Manual JSON Serialization

For small projects or simple DTOs, hand-written fromJson and toJson methods work with zero extra dependencies:

class UserProfile {
  final int id;
  final String email;
  final String? bio;
  final DateTime createdAt;

  const UserProfile({
    required this.id,
    required this.email,
    this.bio,
    required this.createdAt,
  });

  // Factory constructor: Converts Map<String, dynamic> -> UserProfile
  factory UserProfile.fromJson(Map<String, dynamic> json) {
    return UserProfile(
      id: json['id'] as int,
      email: json['email'] as String,
      bio: json['bio'] as String?,
      createdAt: DateTime.parse(json['created_at'] as String),
    );
  }

  // Converts UserProfile -> Map<String, dynamic> for POST/PUT payloads
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'email': email,
      'bio': bio,
      'created_at': createdAt.toIso8601String(),
    };
  }
}

3. Automated Serialization with json_serializable

For enterprise apps with hundreds of API entities, manual serialization is error-prone. json_serializable generates serialization logic during dart run build_runner build.

import 'package:json_annotation/json_annotation.dart';

part 'order_model.g.dart'; // Generated file target

@JsonSerializable()
class OrderModel {
  final String orderId;
  
  @JsonKey(name: 'total_amount_cents')
  final int amountCents;

  @JsonKey(defaultValue: 'PENDING')
  final String status;

  OrderModel({
    required this.orderId,
    required this.amountCents,
    required this.status,
  });

  factory OrderModel.fromJson(Map<String, dynamic> json) => _$OrderModelFromJson(json);
  Map<String, dynamic> toJson() => _$OrderModelToJson(this);
}

4. Modern Immutable Models with Freezed

Freezed combines code-generation, deep immutability, copyWith, structural equality (==), and union types:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'transaction.freezed.dart';
part 'transaction.g.dart';

@freezed
abstract class Transaction with _$Transaction {
  const factory Transaction({
    required String id,
    required double amount,
    @Default(false) bool isSettled,
    @JsonKey(name: 'recipient_name') required String recipient,
  }) = _Transaction;

  factory Transaction.fromJson(Map<String, dynamic> json) => _$TransactionFromJson(json);
}

Freezed Capabilities

void demonstrateFreezed() {
  final tx1 = Transaction(id: 'TX101', amount: 50.0, recipient: 'Alice');

  // 1. Immutable modification via copyWith:
  final tx2 = tx1.copyWith(isSettled: true);

  // 2. Structural Value Equality (No custom hash code needed!):
  final tx3 = Transaction(id: 'TX101', amount: 50.0, recipient: 'Alice');
  print(tx1 == tx3); // ✅ true (compares values, not pointer memory addresses)

  // 3. Readable toString representation:
  print(tx1); // Transaction(id: TX101, amount: 50.0, isSettled: false, recipient: Alice)
}

❓ Knowledge Check

Knowledge Check

Why does Flutter not support dynamic reflection libraries like dart:mirrors for JSON serialization?

Knowledge Check

What is the primary architectural advantage of using the Freezed package for domain models?

On this page