Dart: converting _InternalLinkedHashMap<dynamic, dynamic> in constructor fails

Viewed 27

I am new to Dart and trying to deserialize some json, but I can't quite figure out the trick.

I am able to cast the Map in main as shown, but the commented code does not work and I can't figure out why. I feel like there must be an easier way to do this (outside of using a package for code generation), but I'm not sure what that is.

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

class Book {
    final String title;
    final String path;
    
    Book(this.title, this.path);
    
    Book.fromJson(Map<String, dynamic> content)
        : title = content['title'],
          path = content['path'];
          
    Map<String, dynamic> toJson() =>
        {
            'title': title,
            'path': path,
        };
        
    String toString() {
        return '{ title: $title, path: $path }';
    }
}

class Books {
    
    final Map<String, Book> bookList;
    
    Books(this.bookList);
    
//    Books.fromJson(Map<String, dynamic> content)
//        : bookList = Map<String, Book>.from(jsonDecode(jsonDecode(content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));
    
    Map<String, dynamic> toJson() =>
        {
            'books': jsonEncode(bookList),
        };
    
    String toString() {
        return bookList.toString();
    }
}

void main() {
    Map<String, Book> bookList = {
        "foo": Book("Foo", "/foo"),
        "bar": Book("Bar", "/bar"),
    };
    Books books = Books(bookList);
    print(books);
    String content = jsonEncode(books);
    print(content);
//    print(Books.fromJson(jsonDecode(content)));
    
    Map<String, Book> m = Map<String, Book>.from(jsonDecode(jsonDecode(content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));
    print(m);
}
1 Answers

Oops, I needed to remove an invocation of jsonDecode from Books.fromJson...

  Books.fromJson(Map<String, dynamic> content)
        : bookList = Map<String, Book>.from(jsonDecode((content)['books']).map((k,v) => MapEntry(k as String, Book.fromJson(v))));
Related