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 392 forks source link

need fromJson with Type #1408

Open phamconganh opened 3 months ago

phamconganh commented 3 months ago

e.g. I have a nullable list ['text', null] and write a safe conversion

@JsonKey(fromJson: safeList<String>)
List<String> property;
List<T> safeList<T extends Object>(dynamic value, {List<T> defaultValue = const []}) =>
    safeNullableList<T>(value) ?? defaultValue;

List<T>? safeNullableList<T extends Object>(dynamic value) {
  if (value is List<T>) return value;
  if (value is List<Object?>) return value.whereType<T>().toList();
  return null;
}