jankuss / genq

Instant Data Class Generation for Dart
MIT License
133 stars 0 forks source link

[Question] Any best practices for parsing types like DateTime? #22

Closed rc8marcelo closed 4 months ago

rc8marcelo commented 4 months ago

I read through the readme and I'm guessing using the @JsonKey() annotation with fromJson and toJson is the way to parse it.

I did something like this:


//Sample model
@Genq(json: true)
class MyModel with _$MyModel {
  factory MyModel({
    @JsonKey(
      fromJson: GenqDateTime.fromJson,
      toJson: GenqDateTime.toJson,
    )
    required GenqDateTime someDate,
  }) = _MyModel ;
}

//toJson fromJson
class GenqDateTime {
  final DateTime value;

  GenqDateTime(this.value);

  static GenqDateTime fromJson(String value) {
    final dateTime = DateTime.parse(value);
    return GenqDateTime(dateTime);
  }

  static String toJson(GenqDateTime enclosedDt) {
    return enclosedDt.value.toIso8601String();
  }
}

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 a DateTime

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

jankuss commented 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();
  }
}
jankuss commented 4 months ago

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:

image

Maybe we should too?

rc8marcelo commented 4 months ago

Would be a nice addition if you did 😃

Thanks for the snippet!

jankuss commented 4 months ago

@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