Sample
json_annotation 4.9.0: Configure JsonSerializable options and enum decoding fallbacks in json_annotation, proving snake_case key enforcement, unknownEnumValue null bypass, and readValue error attribution
Verified sample for pub json_annotation 4.9.0: Configure JsonSerializable options and enum decoding fallbacks in json_annotation, proving snake_case key…
sha256:eabf9843a09e0a2fac2d9fe9f0df3eebd2f3eef2bf42bdd99120e6754d499267
This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured.
How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people.
MIT-0
Execution evidence
The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.
- Evidence basis
- Signed contract pass
- Verification receipts
- 2
- Signing keys that built it
- 2
Declared environment
dart linux x64 dart dart pub
Verification-run environments
| Environment | Contract | Stages | Run |
|---|---|---|---|
| dart 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-17 |
| dart 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-18 |
Case
HOW- Goal
- Configure JsonSerializable options and enum decoding fallbacks in json_annotation, proving snake_case key enforcement, unknownEnumValue null bypass, and readValue error attribution
- Packages
- Symbols
-
- JsonSerializable
- JsonSerializable.fromJson
- FieldRename
- JsonKey.unknownEnumValue
- JsonKey.nullForUndefinedEnumValue
- JsonKey.readValue
- $enumDecode
- $enumDecodeNullable
- $checkedCreate
- $checkedConvert
- $checkKeys
- CheckedFromJsonException
- UnrecognizedKeysException
- MissingRequiredKeysException
- DisallowedNullValueException
- Environment
- dart
- Created
- 2026-08-17T14:38:30Z
Contract
- JsonSerializable.fromJson enforces snake_case option keys and disallowUnrecognizedKeys, throwing a CheckedFromJsonException with badKey true on camelCase Dart property names
- field_rename configuration parses exact enum string identifiers and throws an ArgumentError wrapped in CheckedFromJsonException on non-matching strings like screaming_snake
- $enumDecodeNullable returns the unknownValue fallback for unrecognized wire strings but returns null when the input is null, while non-nullable $enumDecode throws ArgumentError on null inputs even when unknownValue is provided
- JsonKey.nullForUndefinedEnumValue causes $enumDecodeNullable to map unrecognized wire strings to null, but passing an incompatible enum type throws an ArgumentError
- readValue custom extractors allow retrieving values from nested paths or aliases, and type mismatch exceptions are re-attributed to the target model field key in CheckedFromJsonException
- $checkKeys evaluates allowedKeys first, requiredKeys second, and disallowNullValues last, where disallowNullValues ignores completely absent keys unless combined with requiredKeys
- $checkedNew attaches the failing key name to CheckedFromJsonException for missing and disallowed-null keys, but leaves key as null for UnrecognizedKeysException
Files
- NOTES.md
- csx.json
- lib/account_config.dart
- pubspec.lock
- pubspec.yaml
- test/contract.dart
Source
# json_annotation Configuration and Fallback Behavior
## Search Results and Prior Art
Querying `search_known_solution` for `json_annotation` returned sample `sha256:aa7e5100c4783c97efd691bb409fe9cad0feebfb84875a777d81fdc86f5f8fe0`, which investigates hand-written `fromJson`/`toJson` serialisation, DateTime formatting, and unchecked dynamic payload failure modes. This investigation focuses on configuration validation, enum decoding fallbacks, custom readValue extraction, and key constraint mechanics.
## Pinned Release
- Package: `json_annotation`
- Pinned Version: `4.9.0`
- Ecosystem: `pub` (Dart SDK `>=3.5.0 <4.0.0`)
## Observed Configuration Behaviors
### 1. `JsonSerializable.fromJson` Option Key Enforcement
- The configuration model `JsonSerializable` itself is annotated with `@JsonSerializable(checked: true, disallowUnrecognizedKeys: true, fieldRename: FieldRename.snake)`.
- When deserializing a configuration map (such as builder configurations), keys must strictly follow `snake_case` (e.g. `field_rename`, `explicit_to_json`, `generic_argument_factories`).
- Attempting to pass Dart property names in `camelCase` (e.g. `{'fieldRename': 'snake'}`) fails loudly with a `CheckedFromJsonException` wrapping an `UnrecognizedKeysException`, where `badKey` is `true` and `key` is `null`.
- The `field_rename` configuration requires exact string matches against `FieldRename` identifiers (`'none'`, `'kebab'`, `'snake'`, `'pascal'`, `'screamingSnake'`). Passing `'screaming_snake'` fails with an `ArgumentError` wrapped in `CheckedFromJsonException`.
### 2. Enum Decoding Fallbacks with `unknownEnumValue`
- In `$enumDecodeNullable`, configuring `unknownValue` to a fallback enum constant (e.g. `AccountStatus.fallback`) maps unrecognized string payloads to the fallback value.
- However, when the JSON payload contains `null`, `$enumDecodeNullable` returns `null` immediately and bypasses `unknownValue`. Developers expecting `unknownEnumValue` to replace `null` will experience silent propagation of `null`.
- In non-nullable `$enumDecode`, passing `null` throws an `ArgumentError` loudly (`A value must be provided`), regardless of whether an `unknownValue` fallback was configured.
- Passing `JsonKey.nullForUndefinedEnumValue` to `$enumDecodeNullable` maps unknown string values to `null`.
- Passing an incompatible enum type as `unknownValue` throws an `ArgumentError` naming the parameter `unknownValue`.
### 3. Custom Extractor `readValue` and Error Attribution
- `JsonKey.readValue` allows custom extractor functions `Object? Function(Map, String)` to retrieve values from nested objects or alternate keys.
- When an extracted value encounters a type mismatch during downstream casting, `$checkedConvert` wraps the `TypeError` into a `CheckedFromJsonException` that reports the target model field key rather than the nested object path.
### 4. Constraint Check Ordering in `$checkKeys` and `$checkedNew`
- `$checkKeys` enforces validation in strict priority: `allowedKeys` is checked first, `requiredKeys` second, and `disallowNullValues` last.
- `disallowNullValues` only triggers when the key is explicitly present in the map with a `null` value. If the key is completely absent, `disallowNullValues` does not throw unless the key is also listed under `requiredKeys`.
- When wrapped inside `$checkedNew` / `$checkedCreate`, missing keys and disallowed null keys populate `CheckedFromJsonException.key`, whereas unrecognized keys leave `key` as `null` with `badKey: true`.
{"case":{"believed":"A model expects JsonSerializable.fromJson to accept camelCase Dart option names, unknownEnumValue to serve as a fallback when an enum field is null, and disallowNullValues to reject missing keys.","caseId":"case:sha256:8bec34b5518fc672982a7b76f641b6638edbf9ab87221e200ce818869cdcffde","contract":["JsonSerializable.fromJson enforces snake_case option keys and disallowUnrecognizedKeys, throwing a CheckedFromJsonException with badKey true on camelCase Dart property names","field_rename configuration parses exact enum string identifiers and throws an ArgumentError wrapped in CheckedFromJsonException on non-matching strings like screaming_snake","$enumDecodeNullable returns the unknownValue fallback for unrecognized wire strings but returns null when the input is null, while non-nullable $enumDecode throws ArgumentError on null inputs even when unknownValue is provided","JsonKey.nullForUndefinedEnumValue causes $enumDecodeNullable to map unrecognized wire strings to null, but passing an incompatible enum type throws an ArgumentError","readValue custom extractors allow retrieving values from nested paths or aliases, and type mismatch exceptions are re-attributed to the target model field key in CheckedFromJsonException","$checkKeys evaluates allowedKeys first, requiredKeys second, and disallowNullValues last, where disallowNullValues ignores completely absent keys unless combined with requiredKeys","$checkedNew attaches the failing key name to CheckedFromJsonException for missing and disallowed-null keys, but leaves key as null for UnrecognizedKeysException"],"goal":"Configure JsonSerializable options and enum decoding fallbacks in json_annotation, proving snake_case key enforcement, unknownEnumValue null bypass, and readValue error attribution","kind":"HOW","packages":["pkg:pub/json_annotation@4.9.0"],"schemaVersion":1,"symbols":["JsonSerializable","JsonSerializable.fromJson","FieldRename","JsonKey.unknownEnumValue","JsonKey.nullForUndefinedEnumValue","JsonKey.readValue","$enumDecode","$enumDecodeNullable","$checkedCreate","$checkedConvert","$checkKeys","CheckedFromJsonException","UnrecognizedKeysException","MissingRequiredKeysException","DisallowedNullValueException"]},"contractCommand":["dart","test/contract.dart"],"environment":{"arch":"x64","ecosystem":"pub","executionContext":"dart","language":"dart","os":"linux","packageManager":"pub","runtime":"dart","schemaVersion":1},"license":"MIT-0","packages":["pkg:pub/json_annotation@4.9.0"],"schemaVersion":1,"symbols":["JsonSerializable","JsonSerializable.fromJson","FieldRename","JsonKey.unknownEnumValue","JsonKey.nullForUndefinedEnumValue","JsonKey.readValue","$enumDecode","$enumDecodeNullable","$checkedCreate","$checkedConvert","$checkKeys","CheckedFromJsonException","UnrecognizedKeysException","MissingRequiredKeysException","DisallowedNullValueException"],"verifierAdapter":"pub@1"}
import 'package:json_annotation/json_annotation.dart';
enum AccountStatus {
active,
suspended,
pending,
fallback,
}
const accountStatusEnumMap = {
AccountStatus.active: 'active',
AccountStatus.suspended: 'suspended',
AccountStatus.pending: 'pending',
AccountStatus.fallback: 'fallback',
};
/// Custom extractor for nested or aliased display title
Object? readDisplayTitle(Map map, String key) {
if (key == 'display_title') {
return (map['metadata'] as Map?)?['title'] ?? map['title'] ?? map['name'];
}
return map[key];
}
/// Model demonstrating json_annotation configuration options
class AccountConfig {
const AccountConfig({
required this.id,
required this.status,
required this.displayTitle,
this.role,
});
final String id;
final AccountStatus status;
final String displayTitle;
final String? role;
factory AccountConfig.fromJson(Map<String, dynamic> json) =>
$checkedCreate<AccountConfig>(
'AccountConfig',
json,
($checkedConvert) {
$checkKeys(
json,
allowedKeys: const ['id', 'status', 'metadata', 'title', 'name', 'role'],
requiredKeys: const ['id', 'status'],
disallowNullValues: const ['id'],
);
return AccountConfig(
id: $checkedConvert('id', (v) => v as String),
status: $checkedConvert(
'status',
(v) => $enumDecodeNullable(
accountStatusEnumMap,
v,
unknownValue: AccountStatus.fallback,
)!,
),
displayTitle: $checkedConvert(
'display_title',
(v) => (v ?? 'Default') as String,
readValue: readDisplayTitle,
),
role: $checkedConvert('role', (v) => v as String?),
);
},
fieldKeyMap: const {
'displayTitle': 'display_title',
},
);
}
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
json_annotation:
dependency: "direct main"
description:
name: json_annotation
sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1"
url: "https://pub.dev"
source: hosted
version: "4.9.0"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
sdks:
dart: ">=3.5.0 <4.0.0"
name: pub_json_annotation_config
description: Minimal project proving json_annotation configuration behavior.
publish_to: none
environment:
sdk: ^3.5.0
dependencies:
json_annotation: ^4.9.0
import 'package:json_annotation/json_annotation.dart';
import 'package:pub_json_annotation_config/account_config.dart';
void check(bool condition, String message) {
if (!condition) {
throw StateError('Contract assertion failed: $message');
}
}
void main() {
// 1. JsonSerializable.fromJson enforces snake_case option keys and disallowUnrecognizedKeys,
// throwing a CheckedFromJsonException with badKey true on camelCase Dart property names.
final validConfig = JsonSerializable.fromJson(const {
'checked': true,
'disallow_unrecognized_keys': true,
'field_rename': 'snake',
'explicit_to_json': true,
'include_if_null': false,
'generic_argument_factories': true,
});
check(validConfig.checked == true, 'checked should be true');
check(validConfig.disallowUnrecognizedKeys == true, 'disallowUnrecognizedKeys should be true');
check(validConfig.fieldRename == FieldRename.snake, 'fieldRename should be snake');
check(validConfig.explicitToJson == true, 'explicitToJson should be true');
check(validConfig.includeIfNull == false, 'includeIfNull should be false');
check(validConfig.genericArgumentFactories == true, 'genericArgumentFactories should be true');
// Passing camelCase option names fails because JsonSerializable has disallow_unrecognized_keys: true
bool caughtCamelCase = false;
try {
JsonSerializable.fromJson(const {'fieldRename': 'snake'});
} on CheckedFromJsonException catch (e) {
caughtCamelCase = true;
check(e.badKey == true, 'badKey must be true for UnrecognizedKeysException');
check(e.key == null, 'key must be null in CheckedFromJsonException for UnrecognizedKeysException');
check(e.className == 'JsonSerializable', 'className must be JsonSerializable');
check(e.innerError is UnrecognizedKeysException, 'innerError must be UnrecognizedKeysException');
}
check(caughtCamelCase, 'JsonSerializable.fromJson must reject camelCase keys');
// 2. field_rename configuration parses exact enum string identifiers and throws an ArgumentError
// wrapped in CheckedFromJsonException on non-matching strings like screaming_snake.
final screamingConfig = JsonSerializable.fromJson(const {'field_rename': 'screamingSnake'});
check(screamingConfig.fieldRename == FieldRename.screamingSnake, 'fieldRename screamingSnake parsed');
bool caughtInvalidRename = false;
try {
JsonSerializable.fromJson(const {'field_rename': 'screaming_snake'});
} on CheckedFromJsonException catch (e) {
caughtInvalidRename = true;
check(e.key == 'field_rename', 'key must be field_rename');
check(e.className == 'JsonSerializable', 'className must be JsonSerializable');
check(e.innerError is ArgumentError, 'innerError must be ArgumentError');
}
check(caughtInvalidRename, 'field_rename must reject invalid enum strings');
// 3. $enumDecodeNullable returns the unknownValue fallback for unrecognized wire strings but returns
// null when the input is null, while non-nullable $enumDecode throws ArgumentError on null inputs even
// when unknownValue is provided.
final fallbackResult = $enumDecodeNullable(
accountStatusEnumMap,
'archived_status',
unknownValue: AccountStatus.fallback,
);
check(fallbackResult == AccountStatus.fallback, 'Unrecognized wire string resolves to unknownValue fallback');
final nullResult = $enumDecodeNullable(
accountStatusEnumMap,
null,
unknownValue: AccountStatus.fallback,
);
check(nullResult == null, 'null input must return null, NOT unknownValue fallback');
bool caughtNullNonNullable = false;
try {
$enumDecode(
accountStatusEnumMap,
null,
unknownValue: AccountStatus.fallback,
);
} on ArgumentError catch (e) {
caughtNullNonNullable = true;
check(e.message.toString().contains('A value must be provided'), 'ArgumentError on null input');
}
check(caughtNullNonNullable, r'$enumDecode must throw ArgumentError on null input');
final nonNullableFallback = $enumDecode(
accountStatusEnumMap,
'archived_status',
unknownValue: AccountStatus.fallback,
);
check(nonNullableFallback == AccountStatus.fallback, r'$enumDecode fallback for unrecognized non-null value');
// 4. JsonKey.nullForUndefinedEnumValue causes $enumDecodeNullable to map unrecognized wire strings to null,
// but passing an incompatible enum type throws an ArgumentError.
final undefinedMappedToNull = $enumDecodeNullable(
accountStatusEnumMap,
'deleted',
unknownValue: JsonKey.nullForUndefinedEnumValue,
);
check(undefinedMappedToNull == null, 'nullForUndefinedEnumValue maps unrecognized string to null');
bool caughtWrongEnumType = false;
try {
$enumDecodeNullable<AccountStatus, String>(
accountStatusEnumMap,
'unknown_token',
unknownValue: FieldRename.kebab,
);
} on ArgumentError catch (e) {
caughtWrongEnumType = true;
check(e.name == 'unknownValue', 'ArgumentError parameter name should be unknownValue');
}
check(caughtWrongEnumType, r'$enumDecodeNullable must reject unknownValue of incompatible enum type');
// 5. readValue custom extractors allow retrieving values from nested paths or aliases, and type
// mismatch exceptions are re-attributed to the target model field key in CheckedFromJsonException.
final validModel = AccountConfig.fromJson(const {
'id': 'acc_01',
'status': 'unknown_wire_status',
'metadata': {'title': 'Admin Account'},
});
check(validModel.id == 'acc_01', 'id matches');
check(validModel.status == AccountStatus.fallback, 'status mapped to fallback via unknownValue');
check(validModel.displayTitle == 'Admin Account', 'displayTitle extracted via nested readValue');
bool caughtBadReadType = false;
try {
$checkedConvert(
const {'title': 999},
'display_title',
(v) => v as String,
readValue: readDisplayTitle,
);
} on CheckedFromJsonException catch (e) {
caughtBadReadType = true;
check(e.key == 'display_title', 'CheckedFromJsonException must report the target field key');
check(e.innerError is TypeError, 'innerError must be TypeError');
}
check(caughtBadReadType, 'readValue type error must be caught in CheckedFromJsonException');
// 6. $checkKeys evaluates allowedKeys first, requiredKeys second, and disallowNullValues last,
// where disallowNullValues ignores completely absent keys unless combined with requiredKeys.
final absentPayload = <String, dynamic>{'other': 123};
$checkKeys(
absentPayload,
allowedKeys: const ['other', 'missing_key'],
disallowNullValues: const ['missing_key'],
);
bool caughtDisallowedNull = false;
try {
$checkKeys(
const {'missing_key': null},
allowedKeys: const ['missing_key'],
disallowNullValues: const ['missing_key'],
);
} on DisallowedNullValueException catch (e) {
caughtDisallowedNull = true;
check(e.keysWithNullValues.contains('missing_key'), 'keysWithNullValues contains missing_key');
}
check(caughtDisallowedNull, r'$checkKeys must throw DisallowedNullValueException when key is explicitly null');
bool caughtAllowedFirst = false;
try {
$checkKeys(
const {'unexpected': 'val'},
allowedKeys: const ['expected_key'],
requiredKeys: const ['expected_key'],
);
} on UnrecognizedKeysException catch (e) {
caughtAllowedFirst = true;
check(e.unrecognizedKeys.contains('unexpected'), 'unrecognizedKeys contains unexpected');
}
check(caughtAllowedFirst, r'$checkKeys must throw UnrecognizedKeysException before checking requiredKeys');
// 7. $checkedNew attaches the failing key name to CheckedFromJsonException for missing and
// disallowed-null keys, but leaves key as null for UnrecognizedKeysException.
bool checkedMissingKeyNamed = false;
try {
$checkedCreate<String>(
'SampleModel',
const {},
(convert) {
$checkKeys(const {}, requiredKeys: const ['req_id']);
return convert('req_id', (v) => v as String);
},
);
} on CheckedFromJsonException catch (e) {
checkedMissingKeyNamed = true;
check(e.key == 'req_id', 'key must be req_id for MissingRequiredKeysException');
check(e.className == 'SampleModel', 'className must be SampleModel');
check(e.badKey == true, 'badKey must be true');
}
check(checkedMissingKeyNamed, r'$checkedCreate must populate key for MissingRequiredKeysException');
print('All json_annotation configuration contract checks passed successfully.');
}