CodeSampleX

Пример

json_annotation 4.12.0: Write fromJson and toJson by hand in Dart with dart:convert and json_annotation, with no build_runner and no generated file, and find out where an unchecked payload actually fails

Проверенный пример — pub json_annotation 4.12.0: Write fromJson and toJson by hand in Dart with dart:convert and json_annotation, with no build_runner and no…

sha256:aa7e5100c4783c97efd691bb409fe9cad0feebfb84875a777d81fdc86f5f8fe0

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда dart 3 linux x64 dart 3 dart pub

Среды запусков проверки

Окружение Контракт Этапы Запуск
dart 3 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · pub@1
2026-08-14

Кейс

HOW
Цель
Write fromJson and toJson by hand in Dart with dart:convert and json_annotation, with no build_runner and no generated file, and find out where an unchecked payload actually fails
Пакеты
Символы
  • jsonDecode
  • jsonEncode
  • JsonUnsupportedObjectError
  • JsonConverter
  • JsonKey
  • JsonSerializable
  • $checkedCreate
  • $checkedConvert
  • $checkKeys
  • CheckedFromJsonException
  • MissingRequiredKeysException
  • UnrecognizedKeysException
  • DisallowedNullValueException
  • DateTime.parse
  • DateTime.toIso8601String
Окружение
dart 3
Создан
2026-08-14T20:06:25Z

Контракт

  1. assert a payload whose every field has the wrong type still decodes, that reading a field out of it still succeeds because both are typed dynamic, and that the first failure is a TypeError at the first typed use in code that never mentions JSON, with reviver the only hook that runs during the decode itself
  2. assert a decoded array is List<dynamic> and is not a List<String> even when every element is a String, and that the usual .cast<String>() fix defers again into a lazy view whose construction and length succeed with a bad element inside while reading that element throws, where List<String>.from fails at the decode
  3. assert a JSON number is int or double according to how it was spelled, so as int rejects 3.0 and as double rejects 3, that num survives both at the cost of a silent truncation in toInt, and that an integer literal past the 64-bit range decodes as a double with its low digits already gone
  4. assert a missing key reads back as null without throwing and is indistinguishable from an explicit null except through containsKey, that it becomes a TypeError in a non-nullable field and silence in a nullable one, and that $checkKeys separates missing, unrecognized and disallowed-null into three named exceptions before any value is read
  5. assert decoding gives a String and encoding a DateTime throws, that DateTime.parse returns UTC for a numeric offset as well as for a trailing Z so the offset is lost on the way out rather than on the way in, that toIso8601String writes no zone designator at all for a non-UTC value, and that the round trip is not == the original because DateTime's == compares the isUtc flag
  6. assert jsonEncode resolves toJson by dynamic dispatch with no interface involved, that a class without one throws JsonUnsupportedObjectError caused by NoSuchMethodError, and that a toJson returning an unencodable value re-attributes the error to your class with the real offender only reachable through cause
  7. assert $checkedCreate and $checkedConvert turn the same TypeError into a CheckedFromJsonException naming the class and the JSON key, including the key rather than the Dart field name and including a key that was missing, while leaving a good payload untouched
  8. assert @JsonSerializable and @JsonKey change nothing at runtime without the generator, so the declared rename and default value are ignored and the hand-written code is what decides the wire key

Файлы

  • csx.json
  • lib/product.dart
  • probe.dart
  • pubspec.lock
  • pubspec.yaml
  • test/contract_test.dart

Скачать артефакт с исходным кодом (tar.gz)

Исходный сидер

anonymous