Skip to main content

json_factory_runtime_annotation 0.3.1 copy "json_factory_runtime_annotation: ^0.3.1" to clipboard
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.

json_factory_runtime_annotation #

The @jsonFactoryKey() annotation for json_factory_runtime_generator.

Put it on a final String or enum field of a @JsonSerializable class. The generator then registers the class in a mixin that can rebuild it from JSON at runtime, using a key stored in the JSON itself.

@JsonSerializable()
class User {
  @jsonFactoryKey()                       // default mixin: JsonFactoryMixin
  final String factoryKey = 'user';
  ...
}

@JsonSerializable()
class Order {
  @jsonFactoryKey(mixin: 'ApiMixin')      // named mixin
  final String factoryKey = 'order';
  ...
}

To rename a key without breaking JSON written with the old one, add the optional oldKeys. Old keys still decode to the class, and toJson() writes only the current key:

@jsonFactoryKey(oldKeys: ['person'])
final String factoryKey = 'member';

jsonFactoryKey extends JsonKey, so json_serializable writes the key into toJson() ("__type__": "user") and fromJson ignores it.

To keep toJson() plain, put @JsonFactoryKey on the class instead. The generated toJsonForFactory then adds the key:

@JsonFactoryKey('user')
@JsonSerializable()
class User {
  ...
}

Use the field by default, and the class annotation when toJson() has to stay plain. The generator's README compares the two.

Add this package to dependencies and the generator to dev_dependencies. See the generator's README for setup, configuration and the generated API.

1
likes
160
points
--
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Annotations for json_factory_runtime_generator, a build-time JSON factory generator for json_serializable classes.

Repository (GitHub)
View/report issues

Topics

#json #serialization #codegen #annotations #build-runner

License

MIT (license)

Dependencies

json_annotation

More

Packages that depend on json_factory_runtime_annotation