Dart – Save and load data with Json

Learning Dart and searching for a basic and easy way to store some data, I stumbled over this documentation from Flutter. 

Example of a class, which defines the structure to be perstisted:

import 'package:uuid/uuid.dart';

class Person {
  // attributes of a person
  late final String uuid;
  final String firstname;
  final String lastname;
  final DateTime birthday;
  final String street;
  final String plz;
  final String city;

  // constructor with required attributes
  Person(
    this.firstname,
    this.lastname,
    this.birthday,
    this.street,
    this.plz,
    this.city,
  ) {
    uuid = Uuid().v8();
  }

  // convert Person to Json
  Map<String, dynamic> toJson() {
    return {
      '${ATTRIBUTE_UUID}': uuid,
      '${ATTRIBUTE_FIRSTNAME}': firstname,
      '${ATTRIBUTE_LASTNAME}': lastname,
      '${ATTRIBUTE_BIRTHDAY}': birthday.toString(),
      '${ATTRIBUTE_STREET}': street,
      '${ATTRIBUTE_PLZ}': plz,
      '${ATTRIBUTE_CITY}': city,
    };
  }

  // create Person from Json
  Person.fromJson(Map<String, dynamic> json)
    : uuid = json[ATTRIBUTE_UUID] as String,
      firstname = json[ATTRIBUTE_FIRSTNAME] as String,
      lastname = json[ATTRIBUTE_LASTNAME] as String,
      birthday = DateTime.parse(json[ATTRIBUTE_BIRTHDAY] as String),
      street = json[ATTRIBUTE_STREET] as String,
      plz = json[ATTRIBUTE_PLZ] as String,
      city = json[ATTRIBUTE_CITY] as String;

  // Print person as string
  String toString() {
    return 'Person(' +
        '"${ATTRIBUTE_UUID}": "${uuid}"' +
        ', "${ATTRIBUTE_FIRSTNAME}": "${firstname}"' +
        ', "${ATTRIBUTE_LASTNAME}": "${lastname}"' +
        ', "${ATTRIBUTE_BIRTHDAY}": "${birthday.toString()}"' +
        ', "${ATTRIBUTE_STREET}": "${street}"' +
        ', "${ATTRIBUTE_PLZ}": "${plz}"' +
        ', "${ATTRIBUTE_CITY}": "${city}"' +
        ')';
  }

  // Consts with name of the attributes
  static const ATTRIBUTE_UUID = 'uuid';
  static const ATTRIBUTE_FIRSTNAME = 'firstname';
  static const ATTRIBUTE_LASTNAME = 'lastname';
  static const ATTRIBUTE_BIRTHDAY = 'birthday';
  static const ATTRIBUTE_STREET = 'street';
  static const ATTRIBUTE_PLZ = 'plz';
  static const ATTRIBUTE_CITY = 'city';
}

First it defines the attributes of the class. Then there is a simple constructor which creates a unique uuid for each Person instance.

toJson() creates Json from the current attribute values.

Person.fromJson() is a names constructor to create a Person instance from the given Json data.

toString() can be used for logging.

And finally the ATTRIBUTE_* consts are used to define the attribute names for Json.

Following is some code to test the creation, saving and loading of the data with Json:

import 'dart:convert';
import 'dart:io';

import 'package:uuid/uuid.dart';
import 'package:vadentest/src/domain/person.dart';

void main(List<String> args) {
  // generate person list
  final persons = <Person>[];
  int counter = 10;

  do {
    persons.add(
      Person(
        'Max ${counter}',
        'Mustermann',
        DateTime.now(),
        'Musterstraße. 8',
        '12345',
        'Musterstadt',
      ),
    );
    counter--;
  } while (counter > 0);

  print('Persons generated: ${persons.length}');
  final StringBuffer jsonString = StringBuffer('');
  jsonString.write(JsonCodec().encode(persons));
  print('Persons: ${jsonString}');

  // Store it in a file
  final file = File('persons.json');
  file.writeAsStringSync(jsonString.toString());

  // Reload it from file
  String jsonReloaded = file.readAsStringSync();
  List<dynamic> jsonDecoded = JsonCodec().decode(jsonReloaded);
  print('length: ${jsonDecoded.length}');

  // Convert from Json to Person instance
  final personsReloaded = <Person>[];
  jsonDecoded.forEach((entry) {
    print('Entry: ${entry}');
    personsReloaded.add(Person.fromJson(entry));
  });

  print('PersonReloaded: ${personsReloaded.length}');
  personsReloaded.forEach((person) => print(person.toString()));
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre, wie deine Kommentardaten verarbeitet werden.