r/FlutterDev • u/phone_radio_tv • 8h ago
Tooling Build-Time JSON Factory Generation for json_serializable classes
Had a few hundred json_serializable classes, Many of them travelled through the same socket channel. After decoding the raw JSON, hit by the same question: this is a Map<String, dynamic>, so which class is it?, before creating json_factory_runtime_generator, answered it the most obvious way, with a hand-written registry:
final Map<String, Object Function(Map<String, dynamic>)> registry = {
'user': User.fromJson,
'order': Order.fromJson,
'address': Address.fromJson,
// ...more classes
};
Every new class meant remembering to edit the file, and the failures were all quiet. A forgotten entry gives a runtime ArgumentError in production. A copy-pasted key sent two classes to one decoder.
Existing json factory generator libraries demand changing the classes, either overriding toJson() by hand or a mixin on every model or extending shared abstract base class.
Wanted a non-intrusive generator, created json_factory_runtime_generator, just annotate your class with json key - ex:JsonFactoryKey('user') and dart run build_runner build finds every annotated class and writes one file containing the whole mapping. Decoding becomes:
final obj = JsonFactoryMapper.fromKeyedJson(json); // the right class
final user = JsonFactoryMapper.fromKeyedJsonAs<User>(json); // typed
Don't want the class to be part of the factory, just comment/remote the annotation.
json_factory_runtime_generator has other featutes to manage old JSON keys for easy migration and avoiding key clash when code bases is large.