json_factory_runtime_annotation 0.3.1
json_factory_runtime_annotation: ^0.3.1 copied to clipboard
Annotations for json_factory_runtime_generator, a build-time JSON factory generator for json_serializable classes.
Example #
Run dart run build_runner build with json_factory_runtime_generator and json_serializable to generate example.g.dart and the factory mixins.
import 'package:json_annotation/json_annotation.dart';
import 'package:json_factory_runtime_annotation/json_factory_runtime_annotation.dart';
part 'example.g.dart';
@JsonSerializable()
class User {
final String id;
final String name;
const User({required this.id, required this.name});
/// Registers `User` under the key `'user'` in the default
/// `JsonFactoryMixin` mixin (decoded with `JsonFactoryMapper`). `toJson()` writes `"__type__": "user"`.
@jsonFactoryKey()
final String factoryKey = 'user';
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
/// Registered in a separate mixin, `ApiMixin` (decoded with `ApiMapper`). Its key used to be
/// 'purchase'; JSON with "__type__": "purchase" still decodes to `Order`.
@JsonSerializable()
class Order {
final String id;
const Order({required this.id});
@jsonFactoryKey(mixin: 'ApiMixin', oldKeys: ['purchase'])
final String factoryKey = 'order';
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
Map<String, dynamic> toJson() => _$OrderToJson(this);
}
A complete, runnable project is in the generator's example.