Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 61 ยท Real-World Dart

JSON and Serialization

Turn JSON into typed Dart objects and back: jsonDecode, jsonEncode, fromJson and toJson, nested objects, lists and the json_serializable idea.

Almost every real program talks to something that speaks JSON: web APIs, configuration files, saved settings, message queues. JSON is text made of objects, arrays, strings, numbers, booleans and null. Dart code prefers typed objects such as User and Order. Serialization is the work of converting between the two: toJson turns an object into JSON-ready data, and fromJson builds an object from decoded JSON.

This lesson uses only the standard library (dart:convert). It builds on maps, constructors (especially factory constructors) and patterns. The Dart code is read-only; the TypeScript stand-ins follow the same structure so you can run it.

Encoding and decoding

dart:convert has two top-level functions:

DART
import 'dart:convert';

void main() {
  final text = '{"name": "Ada", "age": 36, "tags": ["math", "code"]}';

  final decoded = jsonDecode(text); // dynamic
  print(decoded['name']);           // Ada
  print(decoded['tags'][0]);        // math

  final back = jsonEncode({'id': 7, 'ok': true, 'note': null});
  print(back); // {"id":7,"ok":true,"note":null}
}

jsonDecode returns a dynamic, but what is inside is always one of a small set of types:

JSON Dart value
object Map<String, dynamic>
array List<dynamic>
string String
number int or double
true / false bool
null null

Because the result is dynamic, the compiler cannot check anything you do with it. A typo in a key, or a field that is a string in one response and a number in the next, only fails at run time. The goal of the rest of this lesson is to confine that uncertainty to one small place, the fromJson constructor, so the rest of the program works with real types.

jsonEncode accepts those same types. If it meets an object of your own class, it calls toJson() on it. If the class has no such method, it throws JsonUnsupportedObjectError. To make the output readable, use an encoder with an indent: JsonEncoder.withIndent(' ').convert(data).

A model class

Here is the usual shape of a model with a factory constructor for decoding and a method for encoding:

DART
class User {
  final int id;
  final String name;
  final String? email; // optional field

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

  factory User.fromJson(Map<String, dynamic> json) {
    return 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,
      };
}

Notice the as casts. They turn dynamic into real types and throw a TypeError immediately if the data has the wrong shape, which is better than a mysterious failure much later. as String? accepts either a string or a missing key, because looking up a missing key in a map returns null. The collection if in toJson leaves out email when it is null.

Using it is a round trip:

DART
void main() {
  final user = User.fromJson(jsonDecode('{"id": 1, "name": "Ada"}'));
  print(user.name);               // Ada
  print(jsonEncode(user));        // {"id":1,"name":"Ada"}
}

jsonEncode(user) works because User has a toJson() method.

TypeScript fromJson and toJson (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Nested objects and lists

Real payloads contain objects inside objects and lists of objects. The rule is simple: every class decodes itself and calls the fromJson of the classes it contains.

DART
class Address {
  final String city;
  const Address(this.city);

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

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

class Team {
  final String name;
  final Address office;
  final List<String> members;

  const Team(this.name, this.office, this.members);

  factory Team.fromJson(Map<String, dynamic> json) => Team(
        json['name'] as String,
        Address.fromJson(json['office'] as Map<String, dynamic>),
        (json['members'] as List<dynamic>).cast<String>(),
      );

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

A decoded list has the type List<dynamic>, even if it contains only strings. A List<dynamic> is not a List<String>, so you convert it. .cast<String>() wraps the list lazily and fails on the first bad element when it is read; List<String>.from(list) or list.map(...).toList() copy it, and map is the right choice when each element needs fromJson:

DART
final teams = (json['teams'] as List<dynamic>)
    .map((e) => Team.fromJson(e as Map<String, dynamic>))
    .toList();

You do not need to call office.toJson() explicitly if you pass the object to jsonEncode, because the encoder will call it. Doing it in toJson keeps the method honest: it returns pure maps and lists, which you can test by comparing with a literal.

flowchart LR
    T["JSON text"] -- "jsonDecode" --> D["Map / List<br/>(dynamic)"]
    D -- "Team.fromJson" --> O["Team object"]
    O -- "toJson" --> D2["Map / List"]
    D2 -- "jsonEncode" --> T2["JSON text"]

Text becomes loose maps and lists, then typed objects. The way back mirrors it.

Patterns instead of casts

Dart 3 patterns can check and extract in one step, which gives a better error than a bare cast:

DART
factory User.fromJson(Map<String, dynamic> json) {
  if (json case {'id': int id, 'name': String name}) {
    return User(id: id, name: name, email: json['email'] as String?);
  }
  throw FormatException('Not a valid User', json);
}

The if-case fails cleanly when a key is missing or has the wrong type, and you decide which exception to throw. FormatException is the conventional choice for malformed input, and its second argument keeps the offending data for the error message.

TypeScript Nested models and lists (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Dates, enums and other awkward types

JSON has no date type and no enum type, so you choose a representation and convert at the boundary.

  • Dates: use an ISO 8601 string. date.toIso8601String() writes it and DateTime.parse(text) reads it. Prefer UTC (toUtc()) for data sent between systems.
  • Enums: write the name with status.name and read it back with Status.values.byName(text), which throws an ArgumentError for unknown names. Decide up front what an unknown value from a newer server should do.
  • Numbers: a JSON number with a decimal point decodes to double. A server that sends 5 where you expect 5.0 gives you an int, so cast with (json['price'] as num).toDouble() when either is possible.
  • Big integers: when Dart is compiled to JavaScript, integers beyond 2^53 lose precision. Ids that large travel better as strings.
  • Missing and null: treat "key absent" and "key is null" the same unless the API says otherwise; json['x'] as String? does exactly that.

Code generation with json_serializable

Writing fromJson and toJson by hand is easy for three fields and tedious for thirty. The json_serializable package generates them. You annotate the class and run a build tool once:

DART
import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final int id;
  final String name;

  @JsonKey(name: 'e_mail')
  final String? email;

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

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

Running dart run build_runner build creates user.g.dart with _$UserFromJson and _$UserToJson. The generated code is the same kind of cast-and-assign code you wrote above, so it is fast and has no reflection. @JsonKey renames fields, sets defaults or ignores them. The part line and the packages come from libraries and packages.

Generation pays off when you have many models or when the API changes often. For a handful of small classes, hand-written code is clearer and has no build step. Either way, the idea is identical: one place converts between the untyped and the typed world.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does jsonDecode return, and what does a JSON object become?

    jsonDecode returns dynamic. JSON objects become Map<String, dynamic> and arrays become List<dynamic>.
  2. 2. Why is json['tags'] as List<String> risky for decoded JSON?

    The runtime type of a decoded array is List<dynamic>, which is not a List<String>. Use .cast<String>() or copy the elements.
  3. 3. What makes jsonEncode(user) work for your own class?

    When jsonEncode meets an object it cannot encode directly, it calls toJson(). Dart does not use reflection, so without that method it throws.
  4. 4. How are dates usually stored in JSON from Dart?

    JSON has no date type, so an ISO 8601 string is the common, readable and sortable choice.
  5. 5. What does json_serializable generate?

    You annotate the class, run build_runner, and it writes helper functions such as _$UserFromJson into user.g.dart.

Summary

  • jsonDecode gives dynamic data made of maps, lists, strings, numbers, booleans and null; jsonEncode does the reverse.
  • Put all untyped handling in fromJson factories and toJson methods, so the rest of the code uses real types.
  • Cast decoded values (as int, as String?) or use patterns, and convert List<dynamic> with cast or map.
  • Nested models call each other's fromJson/toJson; dates and enums need an agreed text form.
  • json_serializable generates the same code for you with build_runner.

Next: HTTP clients and servers.