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.55k stars 395 forks source link

[Suggestion] Add a project wide option and a @JsonKey option to customize how far to parse DateTime #1315

Open noriHanda opened 1 year ago

noriHanda commented 1 year ago

Why

Sometimes one wants to parse dart's DateTime object only to Date instead of microseconds, but json_serializable does not have an option to specify this. This applies on both toJson and fromJson.

At the same time, how far one wants to parse DateTime may vary on every usecase.

Suggestion

shilangyu commented 1 year ago

Sounds like something that can be handled with a custom converter that will just drop the precision as you wish.

Can be done like so:

const myCustomAnnotation = JsonSerializable(
  converters: [SecondsDateTimeConverter()],
);

then use @myCustomAnnotation.

To me a setting such as dateTimeToParse is way too specific. I doubt it's json_serializable's goal to provide customization to supported serialized types. If you want different serialization it sounds like a converter usecase.

noriHanda commented 1 year ago

To me this setting is similar to options such as field_rename which can be customized with both build.yaml and @JsonKey. What do you think?

kevmoo commented 1 year ago

@noriHanda – the difference is that you'd need create some model for specifying and configuring arbitrary code that json_serializable doesn't already understand. That gets REALLY tricky!

noriHanda commented 1 year ago

@kevmoo Oh so it's more of a challenge on implementation rather than the idea. Good to know. Thx for the comment :)

kevmoo commented 1 year ago

It's a GREAT idea. If it was easy, I would have done it already. 😄

noriHanda commented 1 year ago

I wish I had enough knowledge and skills...

kevmoo commented 1 year ago

@noriHanda – you'll get there. But jumping in on this package would be CRAZY. I wrote most of it and it's still hard for me to tweak.

noriHanda commented 1 year ago

I see. That does sound super hard indeed.

moshe5745 commented 1 year ago

@noriHanda First of all, if this feature will be implemented it's better to pass @JsonKey a DateFormat.

But I think its unneeded complexity because you can implement it yourself: https://pub.dev/packages/json_serializable#custom-types-and-custom-encoding

Just write your date special parser.