DartIntermediate 2 min read

Dart JSON encoding and models: preserve a typed API contract

Decode untrusted JSON, validate required fields and encode an explicit response shape.

On this page

A model constructor and a JSON map have different contracts. The wire format may be malformed, missing a field or include a newer optional value. Validate at the boundary and keep the rest of the application typed.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
import 'dart:convert';

class Invoice {
  const Invoice(this.id, this.totalPaise);
  final String id;
  final int totalPaise;
  factory Invoice.fromJson(Object? input) {
    if (input case {'id': String id, 'totalPaise': int total}
        when id.isNotEmpty && total >= 0) {
      return Invoice(id, total);
    }
    throw const FormatException('Invalid invoice.');
  }
  Map<String, Object> toJson() => {'id': id, 'totalPaise': totalPaise};
}

void main() {
  final invoice = Invoice.fromJson(jsonDecode('{"id":"INV-7","totalPaise":25000}'));
  print(jsonEncode(invoice.toJson()));
}

Follow the data and control flow

jsonDecode returns values representing the received shape. The factory accepts only the fields and domain values needed for a valid invoice. toJson exposes a deliberate public shape instead of serializing every internal property automatically.

Manual parsing is useful while learning the contract. For larger model sets, code generation can reduce repetition, but generated code still needs schema decisions and tests. Use the FlutterFever JSON-to-Dart tool as a starting point, then review every type and validation rule.

A mistake to avoid

A successful JSON parse proves syntax, not schema or authorization. Do not cast a nested map repeatedly throughout widgets. Also avoid treating a missing value as zero unless zero is the documented domain default; otherwise an invalid invoice may appear free.

Use the FlutterFever JSON to Dart generator to draft a model, then compare it with the validated boundary above.

Practice and verification

Test a negative total, a numeric ID and an unknown extra field. Write a round-trip test and decide whether unknown fields should be preserved, ignored or rejected. Compare manual parsing with generated serialization only after the contract is clear.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.