outcast1000
outcast1000

Reputation: 103

Dart: How to de-serialize a list of objects

I have a class "SnapShot" with some member variables like a DateTime and a double. I have written the fromJson / toJson like this:

class SnapShot {
  SnapShot (this.date, this.value);
  final DateTime date;
  final double value;
  SnapShot.fromJson(Map<String, dynamic> json)
      : date = DateTime.parse(json['date']),
        value = json['value']();

  Map<String, dynamic> toJson() =>
    {
      'date': date.toString(),
      'value': value
    };
}

I need to (de)serialize a list of these objects (List) to/from json file. What is the correct way to do this?

Upvotes: 1

Views: 261

Answers (1)

julemand101
julemand101

Reputation: 31269

This should do the trick:

import 'dart:convert';

class SnapShot {
  SnapShot(this.date, this.value);
  final DateTime date;
  final double value;
  SnapShot.fromJson(Map<String, dynamic> json)
      : date = DateTime.parse(json['date']),
        value = json['value'];

  Map<String, dynamic> toJson() => {'date': date.toString(), 'value': value};

  @override
  String toString() => 'date: $date, value: $value';
}

void main() {
  final list = [SnapShot(DateTime.now(), 0.4), SnapShot(DateTime.now(), 1.5)];
  final asJson = json.encode(list);

  final decodedJson = json.decode(asJson) as List;
  final snapShots = decodedJson.map((map) => SnapShot.fromJson(map)).toList();

  print(snapShots);
}

Upvotes: 1

Related Questions