simc / crimson

Fast, efficient and easy-to-use JSON parser and serializer for Dart.
Apache License 2.0
229 stars 6 forks source link

fromJson factory constructor #11

Closed SunlightBro closed 1 year ago

SunlightBro commented 1 year ago

I really like the factory constructor syntax from json_serializable, to be able to call Model.fromJson(uint8List). I'm aware this would just be syntactic-sugar with out much value, but could help migrating from json_serializable to crimson, and it could be just optionally.

Example what I mean

**If** there is a factory constructor that returns `_$(buffer)` (_or some other name convention_) ```dart @json class Model { // ... factory Model.fromJson(List buffer) => _$Model(buffer); } ``` **then** generate additional extensions like so: ```dart Model _$Model(List buffer) => ModelExt.fromJson(buffer); extension ModelExt on Model { static Model fromJson(List buffer) { final crimson = Crimson(buffer); return crimson.readModel(); } Uint8List toJson() { final writer = CrimsonWriter(); writer.writeModel(this); return writer.toBytes(); } } extension ModelList on List { static List fromJson(List buffer) { final crimson = Crimson(buffer); return crimson.readModelList(); } Uint8List toJson() { final writer = CrimsonWriter(); writer.writeModelList(this); return writer.toBytes(); } } ``` then you can call ```dart final Model model = Model.fromJson(singleModelUint8List); final Uint8List foo = model.toJson(); final List list = ModelList.fromJson(listUint8List); final Uint8List bar = list.toJson(); ```

If this is something you want I can create a PR.

simc commented 1 year ago

I really like this idea. I think it would be a great addition 🙏

SunlightBro commented 1 year ago

@simc After working on it for a while now, the only way to make it work (together with freezed) is to always use @Freezed(fromJson: false, toJson: false)

Example ```dart @Freezed(fromJson: false, toJson: false) class FJFreezed with _$FJFreezed { // ignore: invalid_annotation_target @json const factory FJFreezed({ required String name, required int age, }) = _FJFreezed; factory FJFreezed.fromJson(List buffer) => _$FJFreezedFromJson(buffer); } ```

which makes it quite unintuitive to use.