Serializing JSON Manually in Flutter
Contents
Core Guidelines
- Import
dart:convert: Utilize Flutter's built-in dart:convert library for manual JSON encoding (jsonEncode) and decoding (jsonDecode).
- Enforce Type Safety: Always cast the
dynamic result of jsonDecode() to the expected type, typically Map<String, dynamic> for objects or List<dynamic> for arrays.
- Encapsulate Serialization Logic: Define plain model classes containing properties corresponding to the JSON structure. Implement a
fromJson factory constructor and a toJson method within the model.
- Handle Background Parsing: If parsing large JSON documents (execution time > 16ms), offload the parsing logic to a separate isolate using Flutter's
compute() function to prevent UI jank.
- Throw Exceptions on Failure: When handling HTTP responses, throw an exception if the status code is not successful (e.g., not 200 OK or 201 Created). Do not return
null.
Workflow: Implementing a Serializable Model
Use this checklist to implement manual JSON serialization for a data model.
Task Progress:
- Define the Model: Create a class with properties matching the JSON keys.
- Implement
fromJson: Extract values from the Map and cast them to the appropriate Dart types. Use pattern matching or explicit casting.
- Implement
toJson: Return a Map<String, dynamic> mapping the class properties back to their JSON string keys.
- Validate: Execute unit tests to ensure type safety, autocompletion, and compile-time exception handling function correctly.
Workflow: Fetching and Parsing JSON
Use this conditional workflow when retrieving and parsing JSON from a network request.
Task Progress:
- Execute Request: Use the
http package to perform the network call.
- Validate Response:
- If
response.statusCode == 200 (or 201 for POST), proceed to parsing.
- If the status code indicates failure, throw an
Exception.
- Determine Parsing Strategy:
- If parsing a small payload (e.g., a single object), parse synchronously on the main thread.
- If parsing a large payload (e.g., an array of thousands of objects), use
compute(parseFunction, response.body) to parse in a background isolate.
- Decode and Map: Pass the decoded JSON to your model's
fromJson constructor.
Examples
High-Fidelity Model Implementation
import 'dart:convert';
class User {
final int id;
final String name;
final String email;
const User({
required this.id,
required this.name,
required this.email,
});
// Factory constructor for deserialization
factory User.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'id': int id,
'name': String name,
'email': String email,
} =>
User(
id: id,
name: name,
email: email,
),
_ => throw const FormatException('Failed to load User.'),
};
}
// Method for serialization
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
};
}
}
Synchronous Parsing (Small Payload)
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<User> fetchUser(http.Client client, int userId) async {
final response = await client.get(
Uri.parse('https://api.example.com/users/$userId'),
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
// Decode returns dynamic, cast to Map<String, dynamic>
final Map<String, dynamic> jsonMap = jsonDecode(response.body) as Map<String, dynamic>;
return User.fromJson(jsonMap);
} else {
throw Exception('Failed to load user');
}
}
Background Parsing (Large Payload)
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
// Top-level function required for compute()
List<User> parseUsers(String responseBody) {
final parsed = (jsonDecode(responseBody) as List<dynamic>).cast<Map<String, dynamic>>();
return parsed.map<User>((json) => User.fromJson(json)).toList();
}
Future<List<User>> fetchUsers(http.Client client) async {
final response = await client.get(
Uri.parse('https://api.example.com/users'),
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
// Offload expensive parsing to a background isolate
return compute(parseUsers, response.body);
} else {
throw Exception('Failed to load users');
}
}
1---2name: flutter-implement-json-serialization3description: Create model classes with `fromJson` and `toJson` methods using `dart:convert`. Use when manually mapping JSON keys to class properties for simple data structures.4metadata:5 source: https://skillmd.com/skills/om-scogo/flutter-implement-json-serialization6 model: models/gemini-3.1-pro-preview7 last_modified: Tue, 21 Apr 2026 21:44:50 GMT8---910# Serializing JSON Manually in Flutter1112## Contents13- [Core Guidelines](#core-guidelines)14- [Workflow: Implementing a Serializable Model](#workflow-implementing-a-serializable-model)15- [Workflow: Fetching and Parsing JSON](#workflow-fetching-and-parsing-json)16- [Examples](#examples)1718## Core Guidelines1920- **Import `dart:convert`**: Utilize Flutter's built-in `dart:convert` library for manual JSON encoding (`jsonEncode`) and decoding (`jsonDecode`).21- **Enforce Type Safety**: Always cast the `dynamic` result of `jsonDecode()` to the expected type, typically `Map<String, dynamic>` for objects or `List<dynamic>` for arrays.22- **Encapsulate Serialization Logic**: Define plain model classes containing properties corresponding to the JSON structure. Implement a `fromJson` factory constructor and a `toJson` method within the model.23- **Handle Background Parsing**: If parsing large JSON documents (execution time > 16ms), offload the parsing logic to a separate isolate using Flutter's `compute()` function to prevent UI jank.24- **Throw Exceptions on Failure**: When handling HTTP responses, throw an exception if the status code is not successful (e.g., not 200 OK or 201 Created). Do not return `null`.2526## Workflow: Implementing a Serializable Model2728Use this checklist to implement manual JSON serialization for a data model.2930**Task Progress:**31- [ ] Define the plain model class with `final` properties.32- [ ] Implement the `factory Model.fromJson(Map<String, dynamic> json)` constructor.33- [ ] Implement the `Map<String, dynamic> toJson()` method.34- [ ] Write unit tests for both serialization methods.35- [ ] Run validator -> review type mismatch errors -> fix casting logic.36371. **Define the Model**: Create a class with properties matching the JSON keys.382. **Implement `fromJson`**: Extract values from the `Map` and cast them to the appropriate Dart types. Use pattern matching or explicit casting.393. **Implement `toJson`**: Return a `Map<String, dynamic>` mapping the class properties back to their JSON string keys.404. **Validate**: Execute unit tests to ensure type safety, autocompletion, and compile-time exception handling function correctly.4142## Workflow: Fetching and Parsing JSON4344Use this conditional workflow when retrieving and parsing JSON from a network request.4546**Task Progress:**47- [ ] Execute the HTTP request.48- [ ] Validate the response status code.49- [ ] Determine parsing strategy (Synchronous vs. Isolate).50- [ ] Decode and map the JSON to the model.51521. **Execute Request**: Use the `http` package to perform the network call.532. **Validate Response**: 54 - If `response.statusCode == 200` (or 201 for POST), proceed to parsing.55 - If the status code indicates failure, throw an `Exception`.563. **Determine Parsing Strategy**:57 - If parsing a **small payload** (e.g., a single object), parse synchronously on the main thread.58 - If parsing a **large payload** (e.g., an array of thousands of objects), use `compute(parseFunction, response.body)` to parse in a background isolate.594. **Decode and Map**: Pass the decoded JSON to your model's `fromJson` constructor.6061## Examples6263### High-Fidelity Model Implementation6465```dart66import 'dart:convert';6768class User {69 final int id;70 final String name;71 final String email;7273 const User({74 required this.id,75 required this.name,76 required this.email,77 });7879 // Factory constructor for deserialization80 factory User.fromJson(Map<String, dynamic> json) {81 return switch (json) {82 {83 'id': int id,84 'name': String name,85 'email': String email,86 } => 87 User(88 id: id,89 name: name,90 email: email,91 ),92 _ => throw const FormatException('Failed to load User.'),93 };94 }9596 // Method for serialization97 Map<String, dynamic> toJson() {98 return {99 'id': id,100 'name': name,101 'email': email,102 };103 }104}105```106107### Synchronous Parsing (Small Payload)108109```dart110import 'dart:convert';111import 'package:http/http.dart' as http;112113Future<User> fetchUser(http.Client client, int userId) async {114 final response = await client.get(115 Uri.parse('https://api.example.com/users/$userId'),116 headers: {'Accept': 'application/json'},117 );118119 if (response.statusCode == 200) {120 // Decode returns dynamic, cast to Map<String, dynamic>121 final Map<String, dynamic> jsonMap = jsonDecode(response.body) as Map<String, dynamic>;122 return User.fromJson(jsonMap);123 } else {124 throw Exception('Failed to load user');125 }126}127```128129### Background Parsing (Large Payload)130131```dart132import 'dart:convert';133import 'package:flutter/foundation.dart';134import 'package:http/http.dart' as http;135136// Top-level function required for compute()137List<User> parseUsers(String responseBody) {138 final parsed = (jsonDecode(responseBody) as List<dynamic>).cast<Map<String, dynamic>>();139 return parsed.map<User>((json) => User.fromJson(json)).toList();140}141142Future<List<User>> fetchUsers(http.Client client) async {143 final response = await client.get(144 Uri.parse('https://api.example.com/users'),145 headers: {'Accept': 'application/json'},146 );147148 if (response.statusCode == 200) {149 // Offload expensive parsing to a background isolate150 return compute(parseUsers, response.body);151 } else {152 throw Exception('Failed to load users');153 }154}155```