fromJson static method

BookInfo fromJson(
  1. Map<String, dynamic> json, {
  2. bool reschemeImageLinks = false,
})

Implementation

static BookInfo fromJson(
  Map<String, dynamic> json, {
  bool reschemeImageLinks = false,
}) {
  final publishedDateArray =
      ((json['publishedDate'] as String?) ?? '0000-00-00').split('-');

  // initialize datetime variable
  DateTime? publishedDate;
  if (publishedDateArray.isNotEmpty) {
    // initialize date
    int year = int.parse(publishedDateArray[0]);
    int month = 1;
    int day = 1;

    // now test the date string
    if (publishedDateArray.length == 1) {
      // assume we have only the year
      year = int.parse(publishedDateArray[0]);
    }
    if (publishedDateArray.length == 2) {
      // assume we have the year and maybe the month (this could be just a speculative case)
      year = int.parse(publishedDateArray[0]);
      month = int.parse(publishedDateArray[1]);
    }
    if (publishedDateArray.length == 3) {
      // assume we have year-month-day
      year = int.parse(publishedDateArray[0]);
      month = int.parse(publishedDateArray[1]);
      day = int.parse(publishedDateArray[2]);
    }
    publishedDate = DateTime(year, month, day);
  }

  final imageLinks = <String, Uri>{};
  (json['imageLinks'] as Map<String, dynamic>?)?.forEach((key, value) {
    Uri uri = Uri.parse(value.toString());
    if (reschemeImageLinks) {
      if (uri.isScheme('HTTP')) {
        uri = Uri.parse(value.toString().replaceAll('http://', 'https://'));
      }
    }
    imageLinks.addAll({key: uri});
  });

  return BookInfo(
    title: json['title'] ?? '',
    subtitle: json['subtitle'] ?? '',
    authors: ((json['authors'] as List<dynamic>?) ?? []).toStringList(),
    publisher: json['publisher'] ?? '',
    averageRating: ((json['averageRating'] ?? 0) as num).toDouble(),
    categories: ((json['categories'] as List<dynamic>?) ?? []).toStringList(),
    contentVersion: json['contentVersion'] ?? '',
    description: json['description'] ?? '',
    language: json['language'] ?? '',
    maturityRating: json['maturityRating'] ?? '',
    pageCount: json['pageCount'] ?? 0,
    ratingsCount: json['ratingsCount'] ?? 0,
    publishedDate: publishedDate,
    rawPublishedDate: (json['publishedDate'] as String?) ?? '',
    imageLinks: imageLinks,
    industryIdentifiers: ((json['industryIdentifiers'] ?? []) as List)
        .map((i) => IndustryIdentifier.fromJson(i))
        .toList(),
    previewLink: Uri.parse(json['previewLink']),
    infoLink: Uri.parse(json['infoLink']),
    canonicalVolumeLink: Uri.parse(json['canonicalVolumeLink']),
  );
}