Flutter如何将嵌套JSON映射为数据模型并访问属性,合并日期生成DateTime?
解决方案
1. 手动创建Flutter数据模型
我们先创建单条书籍数据的Book类,再创建外层包含书籍列表的响应模型,同时通过getter实现年月字段合并为DateTime对象的逻辑:
class Book { final int bookId; final String bookName; final int yearPublished; final int monthPublished; final int weekPublished; // 直接合并年月生成DateTime对象,无日期字段时默认日为1即可 DateTime get publishDateTime => DateTime(yearPublished, monthPublished, 1); Book({ required this.bookId, required this.bookName, required this.yearPublished, required this.monthPublished, required this.weekPublished, }); // JSON转模型方法 factory Book.fromJson(Map<String, dynamic> json) { return Book( bookId: json['book_id'] as int, bookName: json['book_name'] as String, yearPublished: json['year_published'] as int, monthPublished: json['month_published'] as int, weekPublished: json['week_published'] as int, ); } // 可选:模型转JSON方法 Map<String, dynamic> toJson() { return { 'book_id': bookId, 'book_name': bookName, 'year_published': yearPublished, 'month_published': monthPublished, 'week_published': weekPublished, }; } } // 外层包含books数组的响应模型 class BooksResponse { final List<Book> books; BooksResponse({required this.books}); factory BooksResponse.fromJson(Map<String, dynamic> json) { var booksList = json['books'] as List; List<Book> parsedBooks = booksList.map((item) => Book.fromJson(item)).toList(); return BooksResponse(books: parsedBooks); } }
如果你不想手写映射逻辑避免出错,可以使用官方
json_serializable包自动生成fromJson/toJson代码,使用逻辑和上述手动实现的完全一致。
2. 模型调用与属性访问
// 假设你拿到的原始JSON数据存在rawJson变量中 Map<String, dynamic> rawJson = { "books": [ { "book_id": 1, "book_name": "Harry Potter and the philosopher's stone", "year_published": 1997, "month_published": 6, "week_published": 25, }, { "book_id": 2, "book_name": "Harry Potter and the chamber of secrets", "year_published": 1998, "month_published": 7, "week_published": 26, }, ] }; // 映射为模型对象 BooksResponse response = BooksResponse.fromJson(rawJson); // 属性访问示例 // 读取第一本书的名称 String firstBookName = response.books[0].bookName; // 读取第一本书合并后的发布日期 DateTime firstPublishTime = response.books[0].publishDateTime; // 读取第二本书的发布年份 int secondBookYear = response.books[1].yearPublished;
内容的提问来源于stack exchange,提问作者FDjawid
相关产品推荐
相关产品推荐

