npx skills add ...
npx skills add flutter/skills --skill flutter-implement-json-serialization
npx skills add flutter/skills --skill flutter-implement-json-serialization
Create model classes with `fromJson` and `toJson` methods using `dart:convert`. Use when manually mapping JSON keys to class properties for simple data structures.
The same skill content is published under more than one repo. The install counts are split across them; any of these commands works.
dart:convert: Utilize Flutter's built-in dart:convert library for manual JSON encoding (jsonEncode) and decoding (jsonDecode).dynamic result of jsonDecode() to the expected type, typically Map<String, dynamic> for objects or List<dynamic> for arrays.fromJson factory constructor and a toJson method within the model.compute() function to prevent UI jank.null.Use this checklist to implement manual JSON serialization for a data model.
Task Progress:
final properties.factory Model.fromJson(Map<String, dynamic> json) constructor.Map<String, dynamic> toJson() method.fromJson: Extract values from the Map and cast them to the appropriate Dart types. Use pattern matching or explicit casting.toJson: Return a Map<String, dynamic> mapping the class properties back to their JSON string keys.Use this conditional workflow when retrieving and parsing JSON from a network request.
Task Progress:
http package to perform the network call.response.statusCode == 200 (or 201 for POST), proceed to parsing.Exception.compute(parseFunction, response.body) to parse in a background isolate.fromJson constructor.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');
}
}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');
}
}