### Complete build.yaml Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md This example demonstrates a comprehensive `build.yaml` configuration, including settings for `source_gen` and `json_serializable` builders with various options enabled. ```yaml targets: $default: builders: source_gen|combining_builder: options: ignore_for_file: - lines_longer_than_80_chars - inference_failure_on_function_invocation - inference_failure_on_collection_literal json_serializable: generate_for: - lib/** - test/** options: checked: true disallowUnrecognizedKeys: true fieldRename: snake includeIfNull: false genericArgumentFactories: false createJsonSchema: false ``` -------------------------------- ### Class-Level Application Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Demonstrates applying a `JsonConverter` to an entire class using the `converters` parameter in `@JsonSerializable`. ```APIDOC ## Class-Level Application ### Description Apply a `JsonConverter` to all compatible fields within a class by listing it in the `converters` argument of `@JsonSerializable`. ### Example ```dart class DurationConverter extends JsonConverter { const DurationConverter(); @override Duration fromJson(int milliseconds) => Duration(milliseconds: milliseconds); @override int toJson(Duration duration) => duration.inMilliseconds; } @JsonSerializable(converters: [DurationConverter()]) class Task { final String title; final Duration estimatedTime; Task({required this.title, required this.estimatedTime}); factory Task.fromJson(Map json) => _$TaskFromJson(json); Map toJson() => _$TaskToJson(this); } ``` ``` -------------------------------- ### AddressConverter Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Example of a `JsonConverter` for a custom `Address` class, converting between `Address` and a `Map`. This converter is applied to a field. ```dart class AddressConverter extends JsonConverter> { const AddressConverter(); @override Address fromJson(Map json) => Address( street: json['street'] as String, city: json['city'] as String, zipCode: json['zip'] as String, ); @override Map toJson(Address address) => { 'street': address.street, 'city': address.city, 'zip': address.zipCode, }; } ``` -------------------------------- ### Field-Level Application Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Shows how to apply a `JsonConverter` to specific fields within a class using the converter as a field annotation. ```APIDOC ## Field-Level Application ### Description Apply a `JsonConverter` to individual fields by annotating the field with the converter instance. ### Example ```dart class UriConverter extends JsonConverter { const UriConverter(); @override Uri fromJson(String json) => Uri.parse(json); @override String toJson(Uri uri) => uri.toString(); } @JsonSerializable() class WebResource { final String title; @UriConverter() final Uri url; @UriConverter() final Uri? favicon; factory WebResource.fromJson(Map json) => _$WebResourceFromJson(json); Map toJson() => _$WebResourceToJson(this); } ``` ``` -------------------------------- ### UriConverter Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Example of a `JsonConverter` implementation for the `Uri` type, converting between `Uri` and `String`. Apply this converter to individual fields using the `@UriConverter()` annotation. ```dart class UriConverter extends JsonConverter { const UriConverter(); @override Uri fromJson(String json) => Uri.parse(json); @override String toJson(Uri uri) => uri.toString(); } @JsonSerializable() class WebResource { final String title; @UriConverter() final Uri url; @UriConverter() final Uri? favicon; factory WebResource.fromJson(Map json) => _$WebResourceFromJson(json); Map toJson() => _$WebResourceToJson(this); } ``` -------------------------------- ### Example Usage of $enumDecode Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/enum-helpers.md Example demonstrating how $enumDecode is used internally for enum deserialization. This code is typically generated and not called directly by users. ```dart // Generated code for enum deserialization enum Status { active, inactive, pending } const _$StatusEnumMap = { Status.active: 'active', Status.inactive: 'inactive', Status.pending: 'pending', }; Status _decodeStatus(String jsonValue) => $enumDecode(_$StatusEnumMap, jsonValue); ``` -------------------------------- ### ColorConverter Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Example of a `JsonConverter` for the `Color` type, converting between `Color` and a hexadecimal string representation. This converter is applied to individual fields. ```dart class ColorConverter extends JsonConverter { const ColorConverter(); @override Color fromJson(String json) => Color(int.parse(json.substring(1), radix: 16)); @override String toJson(Color color) => '#${color.value.toRadixString(16).padLeft(8, '0')}'; } @JsonSerializable() class Theme { @ColorConverter() final Color primaryColor; @ColorConverter() final Color accentColor; } ``` -------------------------------- ### Separate Targets for Different Configurations Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Configure different build targets with distinct json_serializable settings. This example defines separate configurations for 'models' and 'api' directories. ```yaml targets: models: builders: json_serializable: generate_for: - lib/models/** options: checked: true api: builders: json_serializable: generate_for: - lib/api/** options: checked: false explicitToJson: true ``` -------------------------------- ### Example Custom fromJson Function for DateTime Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/types.md An example of a custom `fromJson` function that parses a string representation into a `DateTime` object. ```dart @JsonKey(fromJson: _dateFromString) final DateTime date; static DateTime _dateFromString(Object? json) => DateTime.parse(json as String); ``` -------------------------------- ### Watch for Changes with Build Runner Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Starts the build_runner in watch mode to automatically rebuild when source files change. ```bash dart run build_runner watch ``` -------------------------------- ### Simple Enum Example with json_serializable Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/tool/readme/readme_template.md Demonstrates basic enum serialization using `JsonEnum` and `JsonValue` annotations. Ensure `json_annotation` is at least version 4.2.0. ```dart import 'package:json_annotation/json_annotation.dart'; enum Status { unknown, pending, complete, failed, } @JsonEnum(fieldRename: FieldRename.snake) enum Color { red, green, blue, } @JsonEnum() enum StatusWithValues { @JsonValue('UNKNOWN') unknown, @JsonValue(1) pending, @JsonValue(2) complete, @JsonValue(3) failed, } ``` -------------------------------- ### SafeIntConverter Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Example of a `JsonConverter` for safely converting various types to an `int`. This converter handles `int`, `String`, and `double` inputs for JSON deserialization. ```dart class SafeIntConverter extends JsonConverter { const SafeIntConverter(); @override int fromJson(dynamic json) { if (json is int) return json; if (json is String) return int.parse(json); if (json is double) return json.toInt(); throw FormatException('Cannot convert $json to int'); } @override dynamic toJson(int value) => value; } ``` -------------------------------- ### Build Configuration for json_serializable Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/README.md Configure code generation options for `json_serializable` by setting values in `build.yaml`. This example shows common options like `any_map`, `checked`, `create_factory`, and `create_to_json`. ```yaml targets: $default: builders: json_serializable: options: # Options configure how source code is generated for every # `@JsonSerializable`-annotated class in the package. # # The default value for each is listed. any_map: false checked: false constructor: "" create_factory: true create_field_map: false create_json_keys: false create_json_schema: false create_per_field_to_json: false create_to_json: true date_time_utc: false disallow_unrecognized_keys: false explicit_to_json: false field_rename: none generic_argument_factories: false ignore_unannotated: false include_if_null: true ``` -------------------------------- ### Part File Generation Setup Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Configure generated files using the 'part' directive. The source file declares 'part "user.g.dart";' and the generated file uses 'part of "user.dart";'. ```dart // lib/models/user.dart import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; @JsonSerializable() class User { // ... } ``` ```dart // lib/models/user.g.dart part of 'user.dart'; // Generated code User _$UserFromJson(Map json) => ... ``` -------------------------------- ### Global Code Generation Configuration Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Configure which files trigger code generation using glob patterns in build.yaml. This example includes the lib directory and a specific test directory. ```yaml json_serializable: generate_for: - lib/** - test/models/** - example/lib/** ``` -------------------------------- ### Example Custom toJson Function for DateTime Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/types.md An example of a custom `toJson` function that converts a `DateTime` object into an ISO 8601 string. ```dart @JsonKey(toJson: _dateToString) final DateTime date; static String _dateToString(DateTime date) => date.toIso8601String(); ``` -------------------------------- ### Example Custom readValue Function Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/types.md An example of a custom `readValue` function that attempts to extract a value from a map using the provided key, an alternative key, or a fallback key. ```dart @JsonKey(readValue: _readValue) final String value; static Object? _readValue(Map map, String key) => map[key] ?? map['${key}_alt'] ?? map['fallback_$key']; ``` -------------------------------- ### MissingRequiredKeysException Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Thrown when required keys are absent from a JSON map, often triggered by `@JsonKey(required: true)`. This example shows how to catch the exception and inspect the missing keys. ```dart @JsonSerializable() class Order { @JsonKey(required: true) final String orderId; @JsonKey(required: true) final double total; final String? notes; // Optional } try { Order.fromJson({'total': 99.99}); // Missing 'orderId' } on MissingRequiredKeysException catch (e) { print(e.missingKeys); // ['orderId'] print(e.message); // "Required keys are missing: orderId." } ``` -------------------------------- ### DurationConverter Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-converter.md Example of a `JsonConverter` implementation for the `Duration` type, converting between `Duration` and milliseconds (int). Apply this converter at the class level using the `converters` parameter in `@JsonSerializable`. ```dart class DurationConverter extends JsonConverter { const DurationConverter(); @override Duration fromJson(int milliseconds) => Duration(milliseconds: milliseconds); @override int toJson(Duration duration) => duration.inMilliseconds; } @JsonSerializable(converters: [DurationConverter()]) class Task { final String title; final Duration estimatedTime; Task({required this.title, required this.estimatedTime}); factory Task.fromJson(Map json) => _$TaskFromJson(json); Map toJson() => _$TaskToJson(this); } ``` -------------------------------- ### App Configuration Input for JsonLiteralGenerator Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Example of a Dart getter annotated with @JsonLiteral, pointing to a JSON file to be embedded. ```dart @JsonLiteral('config.json', asConst: true) Map get appConfig => _$appConfigJsonLiteral; ``` -------------------------------- ### Programmatic Generation Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Generate JSON serialization code programmatically for testing or custom build systems. This involves creating a `JsonSerializableGenerator` instance and calling its `generateForAnnotatedElement` method. ```dart import 'package:json_serializable/json_serializable.dart'; final generator = JsonSerializableGenerator( config: JsonSerializable(checked: true), ); final result = generator.generateForAnnotatedElement( classElement, constantReader, buildStep, ); ``` -------------------------------- ### Generic Class with genericArgumentFactories Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/types.md Shows an example of a generic class `Response` configured with `genericArgumentFactories: true`, which requires a helper function to handle the generic type `T` during deserialization. ```dart @JsonSerializable(genericArgumentFactories: true) class Response { final T data; Response._$ResponseFromJson( Map json, T Function(Object json) fromJsonT, // Helper for generic type ); } ``` -------------------------------- ### UnrecognizedKeysException Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Thrown when a JSON map contains keys not present in the allowed list, typically triggered by `@JsonSerializable(disallowUnrecognizedKeys: true)`. This example demonstrates catching the exception and accessing its properties. ```dart @JsonSerializable(disallowUnrecognizedKeys: true) class User { final String id; final String name; } try { User.fromJson({'id': '123', 'name': 'John', 'extra': 'field'}); } on UnrecognizedKeysException catch (e) { print(e.unrecognizedKeys); // ['extra'] print(e.allowedKeys); // ['id', 'name'] print(e.message); // "Unrecognized keys: [extra]; supported keys: [id, name]" } ``` -------------------------------- ### Configuring Strict Model Validation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example demonstrates how to configure a model for strict validation using json_serializable annotations like checked, disallowUnrecognizedKeys, required, and disallowNullValue. ```dart @JsonSerializable( checked: true, // Enable detailed error messages disallowUnrecognizedKeys: true, // Strict key validation ) class StrictModel { @JsonKey(required: true) // Require this field final String id; @JsonKey( required: true, disallowNullValue: true, // Disallow null values ) final String name; @JsonKey( includeIfNull: false, // Don't serialize null defaultValue: 'unknown', // Default for missing ) final String status; } ``` -------------------------------- ### Detect Unrecognized Keys with disallowUnrecognizedKeys Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example demonstrates how to trigger an `UnrecognizedKeysException` by using `@JsonSerializable(disallowUnrecognizedKeys: true)` and providing JSON with keys not defined in the class. This is useful for strict validation of incoming JSON data. ```dart @JsonSerializable(disallowUnrecognizedKeys: true) class Config { final String apiKey; } // Throws if JSON contains unexpected keys: Config.fromJson({'apiKey': '...', 'unknownField': 'value'}); ``` -------------------------------- ### Combined Validation Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Illustrates combining multiple validation rules (`disallowUnrecognizedKeys`, `required`, `disallowNullValue`) on a single class. The `$checkKeys` function signature shows how these rules are applied internally. ```dart @JsonSerializable(disallowUnrecognizedKeys: true) class ValidatedModel { @JsonKey(required: true, disallowNullValue: true) final String id; @JsonKey(required: true) final String name; // Can be null but must be present final int? count; // Optional, can be null } // Validates: // 1. Only 'id', 'name', 'count' are allowed // 2. 'id' and 'name' must be present // 3. 'id' must not be null // 4. 'name' can be null $checkKeys( jsonMap, allowedKeys: ['id', 'name', 'count'], requiredKeys: ['id', 'name'], disallowNullValues: ['id'], ); ``` -------------------------------- ### Enhanced Enum Example with json_serializable Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/tool/readme/readme_template.md Shows how to use `JsonEnum` with `valueField` for enhanced enums, allowing serialization based on a specific field within the enum. ```dart import 'package:json_annotation/json_annotation.dart'; enum EnhancedStatus { unknown, pending, complete, failed; // Example of a field that could be used for serialization String get jsonValue => name.toUpperCase(); } @JsonEnum(valueField: 'jsonValue') enum EnhancedStatusWithJsonValueField { unknown, pending, complete, failed; String get jsonValue => name.toUpperCase(); } ``` -------------------------------- ### Registering Custom Type Helpers Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Register custom type helpers programmatically for json_serializable. This example shows how to create a generator instance with a custom helper and specific configuration. ```dart import 'package:json_serializable/json_serializable.dart'; final generator = JsonSerializableGenerator.withDefaultHelpers( [CustomTypeHelper()], config: JsonSerializable(checked: true), ); ``` -------------------------------- ### Enum Serialization Process Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-value-annotation.md Illustrates the internal process of serializing Dart enum members into JSON values. It shows how the enum map is used to find the corresponding JSON representation. ```dart final status = Status.active; // Dart enum // In generated _$StatusToJson: final jsonValue = _$StatusEnumMap[status]; // Returns 'ACTIVE' // JSON output: {'status': 'ACTIVE'} ``` -------------------------------- ### Example Usage of DisallowedNullValueException Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Demonstrates how `DisallowedNullValueException` is thrown when fields marked with `@JsonKey(disallowNullValue: true)` are null in the JSON. It also shows cases where missing keys or nullable fields are handled correctly. ```dart @JsonSerializable() class Contact { @JsonKey(disallowNullValue: true) final String email; @JsonKey(disallowNullValue: true) final String phone; final String? notes; // Nullable, can be null } // Throws - email exists with null value try { Contact.fromJson({'email': null, 'phone': '555-1234'}); } on DisallowedNullValueException catch (e) { print(e.keysWithNullValues); // ['email'] } // OK - missing key is allowed even with disallowNullValue Contact.fromJson({'phone': '555-1234'}); // email uses default // OK - notes is not marked disallowNullValue Contact.fromJson({'email': 'test@example.com', 'phone': '555-1234', 'notes': null}); ``` -------------------------------- ### Conditional Generation with generate_for Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Control code generation for specific directories using the 'generate_for' option in build.yaml. This example targets only model files and applies specific options. ```yaml json_serializable: generate_for: - lib/models/** # Only models - test/fixtures/** # Test fixtures options: # These options apply only to files above checked: true ``` -------------------------------- ### Graceful Degradation with Error Handling Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example shows how to use try-catch blocks to gracefully handle CheckedFromJsonException and FormatException during JSON parsing, returning null or a default instance on failure. ```dart try { final data = StrictModel.fromJson(json); } on CheckedFromJsonException catch (e) { logger.error( 'Failed to parse ${e.className}', error: e.message, field: e.key, ); return null; // or default instance } on FormatException catch (e) { logger.error('Invalid JSON format: $e'); return null; } ``` -------------------------------- ### User Model Input for JsonSerializableGenerator Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Example of a Dart class annotated with @JsonSerializable, which will be used to generate fromJson and toJson methods. ```dart @JsonSerializable() class User { final String id; final String name; final DateTime createdAt; User({ required this.id, required this.name, required this.createdAt, }); factory User.fromJson(Map json) => _$UserFromJson(json); Map toJson() => _$UserToJson(this); } ``` -------------------------------- ### Handling Invalid YAML Syntax Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md Use checkedYamlDecode to parse YAML content. This example shows how it handles invalid YAML syntax. ```dart checkedYamlDecode( 'invalid: yaml: content:', (json) => Config.fromJson(json!), ); ``` -------------------------------- ### Enum Deserialization Process Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-value-annotation.md Explains the internal process of deserializing JSON values into Dart enum members. It highlights the lookup mechanism and error handling when a value is not found. ```dart final jsonValue = 'ACTIVE'; // From JSON // In generated _$StatusFromJson: final status = $enumDecodeNullable(_$StatusEnumMap, jsonValue); // Looks in map: {'active': 'ACTIVE', ...} // Finds 'ACTIVE' and returns Status.active ``` -------------------------------- ### Handling Deserialization Errors in YAML Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example shows how checkedYamlDecode catches deserialization errors within YAML content, such as type mismatches. ```dart checkedYamlDecode( ''' apiKey: "123" port: "not a number" ''', (json) => Config.fromJson(json!), // port: int parsing fails ); ``` -------------------------------- ### Using JsonLiteral with Configuration Data Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-literal-annotation.md Embeds a JSON configuration file as a const Map. This example shows how to access configuration values within a Dart application. ```json { "apiBaseUrl": "https://api.example.com", "timeout": 30000, "retryAttempts": 3, "features": { "analytics": true, "darkMode": false } } ``` ```dart @JsonLiteral('app_config.json', asConst: true) Map get appConfig => _$appConfigJsonLiteral; void main() { final baseUrl = appConfig['apiBaseUrl'] as String; final timeout = appConfig['timeout'] as int; print('Configured to use $baseUrl with ${timeout}ms timeout'); } ``` -------------------------------- ### JsonSerializable with Field Renaming Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-serializable-annotation.md This example shows how to use the `fieldRename` parameter with `FieldRename.snake` to automatically convert Dart field names to snake_case for JSON keys. ```dart @JsonSerializable(fieldRename: FieldRename.snake) class UserProfile { final String firstName; // Serializes as "first_name" final String lastName; // Serializes as "last_name" } ``` -------------------------------- ### Detect Disallowed Null Values with @JsonKey(disallowNullValue: true) Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example shows how `DisallowedNullValueException` is triggered. It defines a class with a field annotated with `@JsonKey(disallowNullValue: true)` and demonstrates calling `fromJson` with a `null` value for that field, which results in an exception. It also highlights that a missing key does not trigger this specific error. ```dart @JsonSerializable() class Contact { @JsonKey(disallowNullValue: true) final String email; } // Throws if key exists with null: Contact.fromJson({'email': null}); // Error! // Does NOT throw if key is missing: Contact.fromJson({}); // OK - uses default or null // Does NOT throw if value is non-null: Contact.fromJson({'email': 'user@example.com'}); // OK ``` -------------------------------- ### YAML Parsing with Enhanced Error Messages Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example demonstrates using checkedYamlDecode within a try-catch block to catch ParsedYamlException and print its formatted message, which includes source location details. ```dart try { final config = checkedYamlDecode( yamlContent, (json) => AppConfig.fromJson(json!), sourceUrl: Uri.file(configFile), ); } on ParsedYamlException catch (e) { print(e.formattedMessage); // Includes file:line:column } ``` -------------------------------- ### Custom Enum Converter with JsonConverter Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-value-annotation.md Shows how to create a custom converter for enums when the JSON values are complex or require custom parsing logic. This example defines a DateEnumConverter for a DateMode enum. ```dart class DateEnumConverter extends JsonConverter { const DateEnumConverter(); @override DateMode fromJson(String json) { // Custom parsing logic return DateMode.values.firstWhere((m) => m.apiValue == json); } @override String toJson(DateMode mode) => mode.apiValue; } ``` -------------------------------- ### Run build_runner to Generate Files Source: https://github.com/google/json_serializable.dart/blob/master/example/README.md Execute this command in your terminal to generate the necessary .g.dart files after annotating your code. This command initiates the build process for code generation. ```console > dart run build_runner build [INFO] ensureBuildScript: Generating build script completed, took 368ms [INFO] BuildDefinition: Reading cached asset graph completed, took 54ms [INFO] BuildDefinition: Checking for updates since last build completed, took 663ms [INFO] Build: Running build completed, took 10ms [INFO] Build: Caching finalized dependency graph completed, took 44ms [INFO] Build: Succeeded after 4687ms with 1 outputs ``` -------------------------------- ### Example Usage of $enumDecodeNullable Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/enum-helpers.md Example showing the internal use of $enumDecodeNullable for nullable enum fields. This function is part of the generated code for handling optional enum values. ```dart // For nullable enum fields enum Priority { high, medium, low } const _$PriorityEnumMap = { Priority.high: 'HIGH', Priority.medium: 'MEDIUM', Priority.low: 'LOW', }; Priority? _decodePriority(String? jsonValue) => $enumDecodeNullable(_$PriorityEnumMap, jsonValue); ``` -------------------------------- ### Load YAML Configuration with Detailed Error Handling Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-yaml.md Loads a YAML configuration file and handles specific exceptions like ParsedYamlException for configuration errors and FileSystemException for file access issues. ```dart void loadYamlConfig(String filePath) { try { final config = AppConfig.fromYamlFile(filePath); print('✓ Config loaded successfully'); } on ParsedYamlException catch (e) { print('✗ Configuration error at ${e.yamlNode?.span?.sourceUrl}'); print(' Line ${e.yamlNode?.span?.start.line}'); print(' ${e.formattedMessage}'); } on FileSystemException catch (e) { print('✗ Cannot read file: $filePath'); } } ``` -------------------------------- ### Build Integration Configuration Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Configure the json_serializable builder in `build.yaml` to integrate with the build_runner system. This specifies the builder factory, import path, and output file extensions. ```yaml targets: $default: builders: json_serializable: import: "package:json_serializable/builder.dart" builder_factories: ["jsonSerializable"] build_extensions: {".dart": ["json_serializable.g.part"]} auto_apply: dependents ``` -------------------------------- ### Configuration File Parsing with Flexible Validation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Parses configuration files where future keys might be added by setting `disallowUnrecognizedKeys: false`. This allows for backward compatibility and flexibility. ```dart @JsonSerializable( disallowUnrecognizedKeys: false, // Allow future config keys ) class AppConfig { @JsonKey(required: true) final String appName; final String? version; // Optional } ``` -------------------------------- ### One-time Build Runner Build Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Executes a one-time build using the build_runner command to generate necessary code. ```bash dart run build_runner build ``` -------------------------------- ### Basic build.yaml Structure Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md This is the basic structure for configuring builders in a `build.yaml` file. The `json_serializable` builder is specified under the `builders` key. ```yaml targets: $default: builders: json_serializable: options: # Builder configuration here ``` -------------------------------- ### Status Enum Input for JsonEnumGenerator Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Example of a Dart enum annotated with @JsonEnum, which will generate a value map. ```dart @JsonEnum() enum Status { active, inactive, pending, } ``` -------------------------------- ### Enable AnyMap Configuration Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Set `anyMap` to `true` to allow `Map` types that are not strictly `Map`. This increases code size but supports maps from various sources like YAML. ```yaml json_serializable: options: anyMap: true ``` -------------------------------- ### Basic YAML Deserialization with File Input Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-yaml.md Demonstrates deserializing YAML content directly from a file using checkedYamlDecode. Ensure the file path is correctly provided for source URL mapping. ```dart @JsonSerializable(checked: true) class AppConfig { final String name; final String version; final Map features; AppConfig({ required this.name, required this.version, required this.features, }); factory AppConfig.fromJson(Map json) => _$AppConfigFromJson(json); factory AppConfig.fromYamlFile(String filePath) { final yamlContent = File(filePath).readAsStringSync(); return checkedYamlDecode( yamlContent, (json) => AppConfig.fromJson(json!), sourceUrl: Uri.file(filePath), ); } } ``` -------------------------------- ### Custom JSON Serialization/Deserialization with toJson/fromJson Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/tool/readme/readme_template.md Illustrates how to add custom `fromJson` constructors and `toJson` methods to a class to handle its JSON serialization and deserialization. ```dart class CustomDateTime { const CustomDateTime(this.dateTime); final DateTime dateTime; factory CustomDateTime.fromJson(int json) => CustomDateTime(DateTime.fromMillisecondsSinceEpoch(json)); int toJson() => dateTime.millisecondsSinceEpoch; } ``` -------------------------------- ### Generated Enum Value Map with FieldRename Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Example of a generated enum value map when FieldRename.screamingSnake is used in the @JsonEnum annotation. ```dart const _$StatusEnumMap = { Status.active: 'ACTIVE', Status.inactive: 'INACTIVE', Status.pending: 'PENDING', }; ``` -------------------------------- ### Nested Object Errors in Checked Mode Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example demonstrates how CheckedFromJsonException is thrown when required keys are missing in nested objects during deserialization. ```dart @JsonSerializable() class Container { final Item item; } @JsonSerializable() class Item { @JsonKey(required: true) final String id; } // JSON: {"item": {}} // In checked mode: // CheckedFromJsonException { // className: "Item", // key: "id", // message: "Required keys are missing: id.", // } ``` -------------------------------- ### Build YAML Configuration Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Configures the json_serializable builder within the build.yaml file, specifying target files and options like checked mode and field renaming. ```yaml # build.yaml targets: $default: builders: json_serializable: generate_for: - lib/** options: checked: true fieldRename: snake ``` -------------------------------- ### Main function for YAML Decoding Source: https://github.com/google/json_serializable.dart/blob/master/checked_yaml/README.md Demonstrates how to use `checkedYamlDecode` to parse YAML content into a Configuration object. Handles file input or direct string input. ```dart void main(List arguments) { final sourcePathOrYaml = arguments.single; String yamlContent; Uri? sourceUri; if (FileSystemEntity.isFileSync(sourcePathOrYaml)) { yamlContent = File(sourcePathOrYaml).readAsStringSync(); sourceUri = Uri.parse(sourcePathOrYaml); } else { yamlContent = sourcePathOrYaml; } final config = checkedYamlDecode( yamlContent, (m) => Configuration.fromJson(m!), sourceUrl: sourceUri, ); print(config); } ``` -------------------------------- ### Handling Non-Map YAML Content Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md checkedYamlDecode throws ParsedYamlException if the YAML content is not a map when allowNull is false. This example demonstrates that scenario. ```dart checkedYamlDecode( 'just a string', (json) => Config.fromJson(json!), ); ``` -------------------------------- ### Accessing ParsedYamlException Properties Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md This example demonstrates how to catch ParsedYamlException and access its properties such as yamlNode for source spans and formattedMessage for display, as well as the innerError. ```dart catch (e) { // Source location: final span = e.yamlNode?.span; // Source span with line/col final formatted = e.formattedMessage; // Error with location // Original error chain: final cause = e.innerError; // YamlException or CheckedFromJsonException } ``` -------------------------------- ### Build Configuration for Validation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/key-validation-helpers.md Sets global validation options for `json_serializable` within the `build.yaml` file. `disallowUnrecognizedKeys: true` applies this rule to all generated classes. ```yaml json_serializable: options: disallowUnrecognizedKeys: true # Applies to all classes ``` -------------------------------- ### Generated Enum Map Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-enum-annotation.md Shows the generated _$StatusEnumMap for a basic enum processed by @JsonEnum(). This map is used internally for serialization and deserialization. ```dart @JsonEnum() enum Status { active, inactive, } // Generates: const _$StatusEnumMap = { Status.active: 'active', Status.inactive: 'inactive', }; // This map is used by generated fromJson/toJson code for enum conversion. ``` -------------------------------- ### Create AppConfig from Optional YAML Content Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-yaml.md A factory constructor to create an AppConfig instance from a nullable YAML string. It uses checkedYamlDecode with allowNull set to true, defaulting to an empty JSON object if the input is null. ```dart factory AppConfig.fromOptionalYaml(String? yamlContent) { return checkedYamlDecode( yamlContent ?? '', (json) => AppConfig.fromJson(json ?? {}), allowNull: true, ); } ``` -------------------------------- ### Custom Generator Subclass Example Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Extend `JsonSerializableGenerator` to create a custom generator. This allows for overriding default behavior or adding custom type helpers, such as `MyCustomTypeHelper`. ```dart class MyJsonGenerator extends JsonSerializableGenerator { MyJsonGenerator({JsonSerializable? config}) : super( config: config, typeHelpers: [MyCustomTypeHelper()], ); } ``` -------------------------------- ### Per-Class Annotation Override Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Use the @JsonSerializable annotation on a class to override global build.yaml settings for that specific class. This example enables checked mode for StrictModel. ```dart // build.yaml says checked: false @JsonSerializable(checked: true) // This class uses checked mode class StrictModel { // ... } @JsonSerializable() // Uses build.yaml settings class DefaultModel { // ... } ``` -------------------------------- ### YAML Configuration Loading Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Defines an AppConfig class that can be deserialized from both JSON and YAML strings using checkedYamlDecode. ```dart @JsonSerializable(checked: true) class AppConfig { final String name; final int version; factory AppConfig.fromJson(Map json) => _$AppConfigFromJson(json); factory AppConfig.fromYaml(String yaml) = checkedYamlDecode(yaml, (json) => AppConfig.fromJson(json!)); } // Load from file final config = AppConfig.fromYaml(File('config.yaml').readAsStringSync()); ``` -------------------------------- ### Generated Enum Map for @JsonEnum Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/enum-helpers.md Example of a generated private map for an enum decorated with @JsonEnum. This map associates enum members with their JSON string representations. ```dart @JsonEnum() enum HttpMethod { get, post, put, delete, } // Generated: const _$HttpMethodEnumMap = { HttpMethod.get: 'get', HttpMethod.post: 'post', HttpMethod.put: 'put', HttpMethod.delete: 'delete', }; ``` -------------------------------- ### Builder Factory Implementation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/generators.md Implement the `jsonSerializable` builder factory function. This function is responsible for creating a `Builder` instance, reading configuration from `BuilderOptions`, and setting up the JSON serialization logic. ```dart Builder jsonSerializable(BuilderOptions options) { final config = JsonSerializable.fromJson(options.config); return jsonPartBuilder(config: config); } ``` -------------------------------- ### Configuration Class with json_serializable Source: https://github.com/google/json_serializable.dart/blob/master/checked_yaml/README.md Defines a Configuration class with annotations for json_serializable, enabling `anyMap`, `checked`, and `disallowUnrecognizedKeys`. ```dart @JsonSerializable(anyMap: true, checked: true, disallowUnrecognizedKeys: true) class Configuration { @JsonKey(required: true) final String name; final int count; Configuration({required this.name, required this.count}) { if (name.isEmpty) { throw ArgumentError.value(name, 'name', 'Cannot be empty.'); } } factory Configuration.fromJson(Map json) => _$ConfigurationFromJson(json); Map toJson() => _$ConfigurationToJson(this); @override String toString() => 'Configuration: ${toJson()}'; } ``` -------------------------------- ### Type Conversion Errors in Checked Mode Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/errors.md In checked mode, CheckedFromJsonException is thrown for type conversion errors during JSON deserialization. This example illustrates an integer parsing failure. ```dart @JsonSerializable() class Data { final int count; final DateTime date; } // JSON: {"count": "not a number", "date": "not a date"} // In checked mode: // CheckedFromJsonException { // className: "Data", // key: "count", // message: "Invalid radix-10 number", // innerError: FormatException, // } ``` -------------------------------- ### Enable JSON Key Constants Generation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Set `createJsonKeys` to `true` to generate a `_$ClassNameJsonKeys` class. This class will contain constants for all JSON keys used in the serialization process. ```yaml json_serializable: options: createJsonKeys: true ``` -------------------------------- ### Custom JSON Key Serialization with toJson/fromJson Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/tool/readme/readme_template.md Demonstrates using `JsonKey` to specify custom top-level or static functions for converting individual fields during JSON serialization and deserialization. ```dart DateTime customFromJson(String json) => DateTime.parse(json); String customToJson(DateTime object) => object.toIso8601String(); @JsonSerializable() class Example { @JsonKey(fromJson: customFromJson, toJson: customToJson) final DateTime timestamp; Example({required this.timestamp}); } ``` -------------------------------- ### Generate Code with build_runner Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/MANIFEST.md Command to initiate code generation for features documented in the library using the Dart build runner. ```bash cd /workspace/home/json_serializable.dart dart run build_runner build ``` -------------------------------- ### Custom JSON Converter Implementation Source: https://github.com/google/json_serializable.dart/blob/master/json_serializable/tool/readme/readme_template.md Shows how to implement `JsonConverter` for custom type conversion, enabling consistent serialization/deserialization logic across multiple fields or types. ```dart import 'package:json_annotation/json_annotation.dart'; class MyDateTimeConverter implements JsonConverter { const MyDateTimeConverter(); @override DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json); @override int toJson(DateTime object) => object.millisecondsSinceEpoch; } @JsonSerializable() class ExampleWithConverter { @MyDateTimeConverter() final DateTime timestamp; ExampleWithConverter({required this.timestamp}); } ``` -------------------------------- ### Enable ToJson Function Generation Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Set `createToJson` to `true` to generate the `_$ClassNameToJson` function. If set to `false`, only the `fromJson` function will be generated. ```yaml json_serializable: options: createToJson: true ``` -------------------------------- ### Create Instance with Checked Deserialization Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-helpers.md Use `$checkedCreate` to generate an instance of a class with comprehensive error handling and validation during deserialization. It takes the class name, source map, a constructor function, and an optional field key map. ```dart T $checkedCreate( String className, Map map, T Function( S Function( String, S Function(Object?), { Object? Function(Map, String)? readValue, }), ) constructor, { Map fieldKeyMap = const {} }, ) ``` ```dart // Generated code for @JsonSerializable(checked: true) User _$UserFromJson(Map json) => $checkedCreate( 'User', json, ( $checkedConvert ) => User( id: $checkedConvert('id', (v) => v as String), name: $checkedConvert('name', (v) => v as String), email: $checkedConvert('email', (v) => v as String?), ), ); ``` -------------------------------- ### Define Custom String Values for Enum Members Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-value-annotation.md Use `@JsonValue` to assign specific string representations to enum members. This example shows how to serialize and deserialize an `Account` class with a `Status` enum. ```dart enum Status { @JsonValue('ACTIVE') active, @JsonValue('INACTIVE') inactive, @JsonValue('SUSPENDED') suspended, } @JsonSerializable() class Account { final String id; final Status status; factory Account.fromJson(Map json) => _$AccountFromJson(json); Map toJson() => _$AccountToJson(this); } // Usage: final account = Account.fromJson({ 'id': '123', 'status': 'ACTIVE', // Deserializes to Status.active }); account.toJson(); // Returns {'id': '123', 'status': 'ACTIVE'} ``` -------------------------------- ### Configure DateTime to UTC Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Set `dateTimeUtc` to `true` to ensure that all `DateTime` fields are serialized in UTC format using `toUtc().toIso8601String()`. If `false`, local time is used. ```yaml json_serializable: options: dateTimeUtc: true ``` -------------------------------- ### Complex Enum and Class Serialization with @JsonValue Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/json-value-annotation.md Demonstrates how to use @JsonValue for enum members and @JsonSerializable for class serialization. This example shows mapping enum values to specific strings and handling required fields during JSON conversion. ```dart @JsonEnum() enum Environment { @JsonValue('dev-us-east-1') developmentUsEast, @JsonValue('staging-eu-west-1') stagingEuWest, @JsonValue('prod-us-west-2') productionUsWest, @JsonValue('prod-ap-southeast-1') productionApSoutheast, } @JsonSerializable(checked: true) class Deployment { @JsonKey(required: true) final String version; @JsonKey(required: true) final Environment target; Deployment({required this.version, required this.target}); factory Deployment.fromJson(Map json) => _$DeploymentFromJson(json); Map toJson() => _$DeploymentToJson(this); } // Usage: final deploy = Deployment.fromJson({ 'version': '1.2.0', 'target': 'prod-us-west-2', // Deserializes to Environment.productionUsWest }); deploy.toJson(); // Returns {'version': '1.2.0', 'target': 'prod-us-west-2'} ``` -------------------------------- ### Specify Constructor for Deserialization Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Use the `constructor` option to specify a named constructor for `fromJson` generation. This is only applicable to classes that have named constructors. ```yaml json_serializable: options: constructor: namedConstructor ``` -------------------------------- ### Basic JSON Serialization Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Defines a User class with basic JSON serialization and deserialization methods using annotations. ```dart @JsonSerializable() class User { final String id; final String name; User({required this.id, required this.name}); factory User.fromJson(Map json) => _$UserFromJson(json); Map toJson() => _$UserToJson(this); } ``` -------------------------------- ### Pubspec.yaml Dependencies Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/configuration.md Declare necessary dependencies for json_serializable. json_annotation is required in dependencies, while build_runner and json_serializable are needed in dev_dependencies for code generation. ```yaml name: my_package version: 1.0.0 dependencies: json_annotation: ^4.12.0 dev_dependencies: build_runner: ^2.10.5 json_serializable: ^6.14.0 ``` -------------------------------- ### Handle YAML Parsing Errors Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/INDEX.md Demonstrates how to catch and print formatted error messages when decoding YAML with potential parsing issues using `checkedYamlDecode`. ```dart try { final config = checkedYamlDecode(yaml, (json) => Config.fromJson(json!)); } on ParsedYamlException catch (e) { print(e.formattedMessage); // Includes line:column } ``` -------------------------------- ### Decode YAML with Constructor and Error Handling Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-yaml.md Use checkedYamlDecode to parse YAML content and pass it to a constructor. It supports specifying a source URL for better error reporting and an option to allow null input. ```dart T checkedYamlDecode( String yamlContent, T Function(Map?) constructor, { Uri? sourceUrl, bool allowNull = false, }) ``` ```dart import 'package:checked_yaml/checked_yaml.dart'; import 'package:json_annotation/json_annotation.dart'; @JsonSerializable(checked: true) class ServerConfig { final String host; final int port; final bool enableSsl; ServerConfig({ required this.host, required this.port, required this.enableSsl, }); factory ServerConfig.fromJson(Map json) => _$ServerConfigFromJson(json); factory ServerConfig.fromYaml(String yamlContent, {Uri? sourceUrl}) => checkedYamlDecode( yamlContent, (json) => ServerConfig.fromJson(json!), sourceUrl: sourceUrl, ); } void main() { final yamlConfig = ''' host: localhost port: 8080 enableSsl: true '''; try { final config = ServerConfig.fromYaml(yamlConfig); print('Configured: ${config.host}:${config.port}'); } on ParsedYamlException catch (e) { print('Configuration error:'); print(e.formattedMessage); } } ``` -------------------------------- ### Checked Mode Helper: $checkedCreate Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/MANIFEST.md Use the $checkedCreate helper function for runtime type checking and validation when creating objects from JSON. This function ensures that the provided JSON data conforms to the expected types and structure, throwing exceptions for any discrepancies. ```dart T $checkedCreate(Map map, T Function(Map json) fromJson) { // Implementation details for checked creation return fromJson(map); } ``` -------------------------------- ### Handling Checked Mode Exceptions Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/api-reference/checked-helpers.md Demonstrates how to catch and inspect `CheckedFromJsonException` when deserializing with checked mode enabled. It shows how to access the field key if the error originated from an `ArgumentError`. ```dart try { final user = User.fromJson(json); } on CheckedFromJsonException catch (e) { // If ArgumentError was thrown for a field, e.key will contain the field name // from the ArgumentError.name property } ``` -------------------------------- ### Enum Value Maps Source: https://github.com/google/json_serializable.dart/blob/master/_autodocs/types.md Demonstrates how enum values are mapped to their corresponding JSON representations (strings or integers) using `Map`. ```dart // String values Map statusMap = { Status.active: 'active', Status.inactive: 'inactive', }; // Integer values Map codeMap = { HttpCode.notFound: 404, HttpCode.unauthorized: 401, }; // Generic value type in $enumDecode $enumDecode( Map enumValues, Object? source, ) ```