NetworkingEasy20 XP4 min read
How do you serialize and deserialize JSON in Flutter?
TL;DR: Manual: implement fromJson/toJson by hand. json_serializable: code-generates toJson/fromJson via annotations + build_runner. Freezed: generates immutable models with copyWith, ==, toJson/fromJson, and union types.
Full Answer
Three Approaches
- โธManual fromJson/toJson: Full control, verbose, no code gen needed. Good for 1-2 simple models
- โธjson_serializable (@JsonSerializable): Code-generated, handles nesting. The standard for most apps
- โธFreezed (@freezed): Generates immutable data classes + JSON + union types. Best for complex domain models
๐ฏ
Always use compute() or Isolate.run() when decoding large JSON payloads (>100KB) to avoid blocking the UI thread.
Code Examples
dartjson_serializable model
Output
// Generated user.g.dart handles snake_case โ camelCase mapping // explicitToJson: true ensures nested objects are serialized too
Common Mistakes
- โForgetting explicitToJson: true โ nested objects serialize as {} without it
- โNot running build_runner after adding/changing fields โ stale generated code causes type errors
Interview Tip
๐ก
Mention the three approaches and when to use each. Show you know that Freezed is a superset of json_serializable โ it generates the annotation boilerplate for you.
#json#serialization#fromJson#toJson#freezed#json-serializable