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

[Question/Feature Request?] Support generics serialization from parent #1316

Open matanshukry opened 1 year ago

matanshukry commented 1 year ago

I'm using jsonserializable, and having an issue with generics. I read on how to "solve" serialization for class A that has generic type T - but I'm thinking on why do I even need to specify some solution, if class A is inside Class B, and class B already knows about the type. Perhaps there's a better way to model it ?

Example:

class MyData<T> {
  final T value;
  final bool preferred;
}

@freezed
class Profile with $Profile {
  const factory Profile({ MyData<Fruit> fruits, MyData<Cake> cakes }) = _Profile;
  // Fruit and Cake are strongly typed enums.

  // .. fromJson
}

So while I understand why the system can't serialize MyData - it should be able to serialize fruits and cakes` variables; right? Any way to do that then?

moshe5745 commented 1 year ago

Check out my issue: https://github.com/google/json_serializable.dart/issues/1318 Maybe the example code can help you in your case.

kevmoo commented 1 year ago

@matanshukry – your case should work – assuming Cake and Fruit have toJson and fromJson

matanshukry commented 1 year ago

@kevmoo both of them are enums, so they don't have toJson and fromJson. But it seem to fail even with structures that do have toJson/fromJson.

Example repo/file: https://github.com/matanshukry/example_json_serialization_generics/blob/master/lib/data.dart

Error:

[SEVERE] json_serializable on lib/data.dart:

Could not generate `fromJson` code for `data`.
To support the type `MyData` you can:
* Use `JsonConverter`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
* Use `JsonKey` fields `fromJson` and `toJson`
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
package:example/data.freezed.dart:116:24
    ╷
116 │   final MyData<Person> data;
    │                        ^^^^
    ╵
[INFO] Running build completed, took 99ms