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

Dynamic parsing with the help of an additional type parameter #1318

Open moshe5745 opened 1 year ago

moshe5745 commented 1 year ago

I successfully achieved dynamic parsing with the help of another parameter in the same JSON. Like this:

@JsonSerializable()
class MySpecialModel {
...
  final DataType type;
 @JsonKey(fromJson: _dataFromJson, readValue: _dataReadValue,)
 final dynamic data;
...

 static Data _dataReadValue(Map json, String key) {
    DataType type = DataType.values.byName(json['type']);
    return Data(type, json[key]);
  }

  static String _dataFromJson(Data value) {
    switch (value.type) {
      case DataType.first:
        return DataFirst.fromJson(value.data);
      case DataType.second:
        return DataSecond.fromJson(value.data);
      case DataType.third:
        return DataThird.fromJson(value.data);
    }
  }

@JsonSerializable()
class Data {
  final DataType type;
  final dynamic data;

  Data(this.type, this.data);
}

This is great! Thank you for your hard work.

The issue is that I have a list of these objects. Like:

@JsonSerializable()
class MyParentSpecialModel {
  final List<MySpecialModel> mySpecialModels;

It would be more suitable for the backend to return the type of data in the parent model. Like:

@JsonSerializable()
class MyParentSpecialModel {
  final DataType type;
  final List<MySpecialModel> mySpecialModels;

So the objects of the list would not have the repeated type over and over again.

How can I achieve this?

kevmoo commented 1 year ago

this is a LONG requested feature

moshe5745 commented 1 year ago

@kevmoo Wow. Do you have an idea how to handle it? Maybe I could try to contribute(with some guidance).