0

I'm using the packages: https://pub.dev/packages/json_annotation, https://pub.dev/packages/json_serializable

I want to encode/decode a list of objects in my flutter app. The class which is in the list is as follows:

@JsonSerializable()
class Trial {
  final ProtocolType type;
  List<List<double>> data;
  @JsonKey()
  final DateTime date;

  Trial({this.type, this.data, this.date});
  Map<String, dynamic> toMap() {
    return {'type': this.type, 'data': this.data, 'date': this.date};
  }

  factory Trial.fromJson(Map<String, dynamic> json) => _$TrialFromJson(json);
  Map<String, dynamic> toJson() => _$TrialToJson(this);
}

I want to decode/encode a list of these items, and I couldn't figure out how else to do it so I made a new class:

@JsonSerializable()
class TrialList {
  final List<Trial> trials;
  TrialList({this.trials});
  factory TrialList.fromJson(List json) => _$TrialListFromJson(json);
  List toJson() => _$TrialListToJson(this);
}

Notice the List toJson() in this new class. It seems Json_serializable only wants me to decode/encode maps, is there any way to support lists?

Jonah Kornberg
  • 153
  • 1
  • 8

1 Answers1

1

Solution:

@JsonSerializable()
class TrialList {
  final List<Trial> trials;
  TrialList({this.trials});
  factory TrialList.fromJson(json) => _$TrialListFromJson({'trials': json});
  List toJson() => _$TrialListToJson(this)['trials'];
}

credit to Null from the /r/FlutterDev discord

Jonah Kornberg
  • 153
  • 1
  • 8