google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.54k stars 393 forks source link

Can't custom JsonConverter with constructor arguments. Error "Generators with constructor arguments are not supported" #1373

Open phuongvt opened 8 months ago

phuongvt commented 8 months ago

When I write DateTimeConverter extends from JsonConverter with constructor arguments. Then use

  @JsonKey(name: 'time')
  @DateTimeConverter(pattern: 'YYYY/MM/dd')
  final DateTime time;

run build_runner build print error "Generators with constructor arguments are not supported"

faisalansari0367 commented 8 months ago

@phuongvt Thanks for this awesome PR. When can we expect this into release?

faisalansari0367 commented 8 months ago

For now If anyone wants to use a same JsonConverter for two purpose You can use a named constructor. For example:

Screenshot 2023-11-27 at 8 26 52 PM

And you can it use it as:

Screenshot 2023-11-27 at 8 27 03 PM
phuongvt commented 6 months ago

@faisalansari0367 : Thank you for your support!

First of all, sorry for the late reply. In my case, I need to define many parameters in JsonConverter structure, and the parameters have too many different values because they are of type String => there can be many "named constructors" that need to be created without rarely reused. For example:

pattern= 'YYYY/MM/dd'
pattern= 'YYYY/MM/dd HH:mm:ss'
pattern= 'YYYY/MM/dd HH:mm'
pattern= 'YYYY-MM-dd'
...

so I still find "Generators with constructor arguments" necessary. I need MR as soon as possible to support my projects

Thank you!

kevmoo commented 6 months ago

Have you considered adding named constructors with the values pre-populated? That should work.

phuongvt commented 6 months ago

@kevmoo yes, I was considering creating 'named constructors' that are often reused. However, I still think supporting 'Generators with constructor arguments' is necessary

kevmoo commented 6 months ago

@kevmoo yes, I was considering creating 'named constructors' that are often reused. However, I still think supporting 'Generators with constructor arguments' is necessary

This will add non-trivial complexity to this package, sadly.

phuongvt commented 6 months ago

@kevmoo What do you think if I create a new class ArgumentsJsonConverter. JsonConverter I will throw an exception "Use ArgumentsJsonConverter to support constructor arguments or define named constructors (#1373)" instead of "Generators with constructor arguments are not supported"

MoralCode commented 4 months ago

i believe I have found a convenient enough workaround.

in your Converter:

  const DecimalIntConverter.tenths() : this(places: -1);
  const DecimalIntConverter({this.places = 0, this.base = 10});

in your type:

   @DecimalIntConverter.tenths() double someValue;