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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.