json_factory_runtime_generator 0.3.2
json_factory_runtime_generator: ^0.3.2 copied to clipboard
Build-time JSON factory generator for json_serializable classes. Decodes JSON to the right class from a key in the JSON, with no base class, mixin or toJson changes.
Example #
A small project that uses json_factory_runtime_generator.
lib/models/:UserandAddressin the defaultJsonFactoryMixinmixin (Addressalso accepts its old key'location'),Order,ApiUserandApiEvent(key from an enum@JsonValue) inApiMixin.build.yaml: writes the mixins tolib/src/factories/json_factory_runtime.g.dart.lib/factories.dart: classes that mix them in. The generatedJsonFactoryMapperandApiMapperclasses can be called directly instead.test/factory_test.dart: round-trips JSON through the factories.
@JsonSerializable()
class User {
final String id;
final String name;
const User({required this.id, required this.name});
@jsonFactoryKey()
final String factoryKey = 'user';
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
final json = const User(id: '1', name: 'Ada').toJson();
// {id: 1, name: Ada, __type__: user}
final user = JsonFactoryMapper.fromKeyedJsonAs<User>(json);
Run it:
dart pub get
dart run build_runner build
dart test