json_annotation_tools 0.1.7
json_annotation_tools: ^0.1.7 copied to clipboard
Transform cryptic JSON parsing errors into crystal-clear, actionable error messages. Perfect companion to json_annotation.
example/main.dart
library;
import 'package:json_annotation_tools/json_annotation_tools.dart';
void main() {
print('š json_annotation_tools Example');
print('=' * 50);
// š¤ CODE GENERATION APPROACH: @SafeJsonParsing()
print('\nš¤ APPROACH 1: @SafeJsonParsing() Code Generation');
print('-' * 30);
final userJson = {
'id': 123,
'name': 'John Doe',
'email': 'john@example.com',
'age': 30,
'isActive': true,
};
print('š With @SafeJsonParsing(), you would write:');
print(' @JsonSerializable()');
print(' @SafeJsonParsing()');
print(' class User { ... }');
print('');
print('š This auto-generates: UserSafeJsonParsing.fromJsonSafe(json)');
print('ā
Enhanced errors built into the generated method!');
print('š See user.dart for the complete model example');
print('šļø Run: dart run build_runner build (to generate code)');
// š± MANUAL APPROACH: Safe Extension Methods
print('\nš± APPROACH 2: Manual Safe Extensions (Alternative)');
print('-' * 30);
try {
// Using safe extension methods - no crashes on type mismatches!
final id = userJson.getSafeInt('id');
final name = userJson.getSafeString('name');
final email = userJson.getSafeString('email');
final age = userJson.getNullableSafeInt('age');
final isActive = userJson.getSafeBool('isActive');
print('ā
SUCCESS: Manual parsing worked!');
print(' ID: $id, Name: $name, Age: $age, Active: $isActive');
} catch (e) {
print('ā Error: $e');
}
// š„ ERROR DEMONSTRATION: See Enhanced Error Messages in Action!
print('\nš„ ERROR DEMONSTRATION: Enhanced Error Messages');
print('-' * 30);
final badJson = {
'id': 'not-a-number', // ā Should be int, got String
'name': 'Jane Doe',
'email': 'jane@example.com',
'age': 25,
'isActive': true,
};
print('\nš Trying to parse invalid JSON (id should be int, got String):');
try {
// š Using manual extension method to show enhanced error
final id = badJson.getSafeInt('id');
print('ā Should have failed but got: $id');
} catch (e) {
print('ā
CAUGHT ENHANCED ERROR MESSAGE:');
print('š½ This is the same enhanced error you get with @SafeJsonParsing():');
final lines = e.toString().split('\n');
for (int i = 0; i < lines.length && i < 12; i++) {
print(' ${lines[i]}');
}
print(' ...');
print('š” Notice: Both approaches give the same detailed diagnosis + solutions!');
}
// š„ MISSING FIELD DEMONSTRATION
print('\nš„ MISSING FIELD: Smart Field Detection');
print('-' * 30);
final incompleteJson = {
'name': 'Bob Wilson',
'email': 'bob@example.com',
// Missing 'id' field
};
print('\nš Trying to get missing field "id":');
try {
// š Using manual extension method to show missing field error
final id = incompleteJson.getSafeInt('id');
print('ā Should have failed but got: $id');
} catch (e) {
print('ā
CAUGHT MISSING FIELD ERROR:');
print('š½ Enhanced missing field message with suggestions:');
final lines = e.toString().split('\n');
for (int i = 0; i < lines.length && i < 10; i++) {
print(' ${lines[i]}');
}
print(' ...');
print('š” Notice: Shows available fields + suggests similar names!');
}
// šÆ REAL-WORLD SCENARIO: Production API Handling
print('\nš PRODUCTION SCENARIO: API Response Handling');
print('-' * 30);
// Simulate different API responses
final apiResponses = [
{'status': 'Valid user response', 'data': userJson},
{'status': 'Type error response', 'data': badJson},
{'status': 'Missing field response', 'data': incompleteJson},
];
for (int i = 0; i < apiResponses.length; i++) {
final response = apiResponses[i];
final status = response['status'] as String;
print('\nš” API Response ${i + 1}: $status');
try {
final data = response['data'] as Map<String, dynamic>;
// š§ Using manual extension methods (same enhanced errors as @SafeJsonParsing!)
final id = data.getSafeInt('id');
final name = data.getSafeString('name');
print(' ā
SUCCESS: Parsed user $name (ID: $id)');
} catch (e) {
print(' ā PARSING FAILED: Enhanced error logged for debugging');
print(' š Error preview: ${e.toString().split('\n').first}');
// š In production, you'd log this to Crashlytics/Sentry:
// crashlytics.recordError(e, null);
// logger.error('User parsing failed', error: e);
}
}
print('\nš Enhanced JSON Parsing Example Complete!');
print('=' * 50);
print('š WHAT YOU LEARNED:');
print('ā
Two approaches: @SafeJsonParsing() code generation + manual extensions');
print('ā
Enhanced errors show exact problem + copy-paste solutions');
print('ā
Perfect for production: detailed errors + graceful handling');
print('ā
Same enhanced error messages with both approaches');
print('\nš¤ @SafeJsonParsing() CODE GENERATION:');
print('⢠Annotate your model with @SafeJsonParsing()');
print('⢠Run: dart run build_runner build');
print('⢠Use: UserSafeJsonParsing.fromJsonSafe(json)');
print('⢠Result: Enhanced errors built into generated method!');
print('\nš NEXT STEPS:');
print('š Full production guide: PRODUCTION_SETUP.md');
print('š± Interactive Flutter demo: example_app/');
print('š Ready to eliminate cryptic JSON errors forever!');
}