json_annotation_tools 0.1.7 copy "json_annotation_tools: ^0.1.7" to clipboard
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!');
}
2
likes
140
points
54
downloads

Publisher

verified publisherkhokan.me

Weekly Downloads

Transform cryptic JSON parsing errors into crystal-clear, actionable error messages. Perfect companion to json_annotation.

Documentation

API reference

License

MIT (license)

Dependencies

analyzer, args, build, flutter, json_annotation, meta, path, source_gen

More

Packages that depend on json_annotation_tools