Skip to content

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

Open
@moshe5745

Description

@moshe5745

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions