Sparround

JSON serialization

In Dart, JSON arrives as a Map<String, dynamic>, which is a type-unsafe shape: write json['naem'] and the compiler stays silent while the failure waits for runtime.

The fix is converting to a domain model at the boundary. Two routes:

  • By handfactory Order.fromJson(Map<String, dynamic> json). No dependency, but tedious and error-prone as the model grows
  • Code generationjson_serializable with build_runner: you write annotations and fromJson/toJson are generated

Either way the conversion belongs in the data layer only; a widget should never see JSON.

Two situations always cause trouble with real APIs:

  • `null` and missing fields — the docs may say "always present", but in practice it will not be. Reflect nullability honestly in the model and supply defaults
  • Type mismatches — a backend sometimes sends a number as a string ("42"). A blind as int cast explodes at runtime; a safe parse helper is needed

These are among the most common findings in API testing, and on the Flutter side they are handled with defensive parsing.

Interview tip. Answer "by hand or code generation?" with a criterion: for two or three small models, hand-writing is simpler and not worth setting up build_runner; with 20+ models or a frequently changing API, generation removes both the tedium and the mistakes. Add a nuance: generated .g.dart files either go into version control or CI has to run build_runner — the team needs a decision either way.

📚 Sources and documentation