Closed rc8marcelo closed 4 months ago
You are on the right track. You can save yourself the extra step of having a GenqDateTime
- you can just convert to a DateTime
directly.
@Genq(json: true)
class User with _$User {
factory User({
required int id,
@JsonKey(
fromJson: DateTimeConverter.fromJson,
toJson: DateTimeConverter.toJson,
)
required DateTime createdAt,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => $UserFromJson(json);
}
class DateTimeConverter {
static DateTime fromJson(String value) {
return DateTime.parse(value);
}
static String toJson(DateTime value) {
return value.toIso8601String();
}
}
I think the use case of using DateTime is common enough to be included within genq without additional effort.
json_serializable
, and thus freezed
already provide support for these types:
Maybe we should too?
Would be a nice addition if you did 😃
Thanks for the snippet!
@rc8marcelo DateTime
support is now available in version 0.4.0, so your custom toJson
/fromJson
won't be needed anymore, and you can rely on genq
generating this code for you.
To get the latest version of genq, you can do:
brew upgrade jankuss/genq/genq
I read through the readme and I'm guessing using the
@JsonKey()
annotation withfromJson
andtoJson
is the way to parse it.I did something like this:
I'm just wondering if this is the right way to go about it? I use freezed normally so I got used to how it auto parses Strings into
DateTime
objects and just wondering if there's a way to do it without having to have a class enclosing aDateTime
I wanted to make the question more broad for other types but the only type I can think of is
DateTime
.Edit: updated sample code