decode method
Parses jsonString and invokes fromJson when the payload is a
JSON object. Returns null for blank payloads and throws a
FormatException when the input is not a JSON object or when parsing
fails.
Implementation
T? decode(String? jsonString) {
try {
if (jsonString == null || jsonString.trim().isEmpty) {
return null;
}
final dynamic decoded = jsonDecode(jsonString);
if (decoded is! Map<String, dynamic>) {
throw const FormatException('Expected a JSON object.');
}
final Map<String, dynamic> map = Map<String, dynamic>.from(decoded);
return _fromJson(map);
} on FormatException catch (error) {
throw FormatException('Failed to parse JSON: ${error.message}');
} catch (error) {
throw FormatException('Failed to parse JSON: $error');
}
}