atreeon / morphy

Provides a clean class definition with extra functionality including; copy with, json serializable, tostring, equals that supports inheritance and polymorphism
3 stars 3 forks source link

Use JsonConverter converters? #2

Open tgrushka opened 6 months ago

tgrushka commented 6 months ago

I was interested in this package until I discovered that the use of JsonConverter classes/annotations on custom fields does not work. JsonSerializable requires specifying converters for fields that have types that are not built into json_serializable. For example, using a type like UuidValue in a field, I'd like to convert it to/from String.

I can do this with freezed, but freezed also does not allow specifying this globally for types or on classes (one has to add the converter to every field). Would give your package an advantage to be able to specify custom converters at the class level and also in build.yaml (which neither freezed nor json_serializable offers).

Example:


class UuidValueConverter extends JsonConverter<UuidValue, String> {
  const UuidValueConverter();

  @override
  UuidValue fromJson(String json) => UuidValue.fromString(json);

  @override
  String toJson(UuidValue object) => object.uuid;
}

@Morphy(converters: [UuidValueConverter()])
abstract class $Pet {
  UuidValue? get id;
  String get name;
}

or build.yaml:

targets:
  $default:
    builders:
      morphy:
        options:
          converters:
            - UuidValueConverter
atreeon commented 6 months ago

Hi @tgrushka, many thanks for trying out the package. You are right this would be beneficial. I'll take a look at this sometime this week and update it. I only recently added the json package and functionality (it is the main reason why I sat on the package for so long) so that part is the area where functionality is likely missing. I think this should be fairly straight forward though.