json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Dynamic parsing with the help of an additional type parameter

Open moshe5745 opened this issue 1 year ago • 2 comments

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?

moshe5745 avatar May 14 '23 19:05 moshe5745

this is a LONG requested feature

kevmoo avatar May 17 '23 02:05 kevmoo

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

moshe5745 avatar May 17 '23 06:05 moshe5745