我有一個 json book 對象,其中包含這些嵌套屬性:
"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,
},
如何將此嵌套的 json 對象映射到數據模型並訪問映射對象的屬性?另外我如何將 year_publishedand 和 month_published 組合到 DateTime 對像中並訪問它?
您可以創建一個如下所示的 Books Model 類:
class BooksModel {
List<Books> books;
BooksModel({this.books});
BooksModel.fromJson(Map<String, dynamic> json) {
if (json['books'] != null) {
books = new List<Books>();
json['books'].forEach((v) {
books.add(new Books.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.books != null) {
data['books'] = this.books.map((v) => v.toJson()).toList();
}
return data;
}
}
class Books {
int bookId;
String bookName;
int yearPublished;
int monthPublished;
int weekPublished;
Books(
{this.bookId,
this.bookName,
this.yearPublished,
this.monthPublished,
this.weekPublished});
Books.fromJson(Map<String, dynamic> json) {
bookId = json['book_id'];
bookName = json['book_name'];
yearPublished = json['year_published'];
monthPublished = json['month_published'];
weekPublished = json['week_published'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['book_id'] = this.bookId;
data['book_name'] = this.bookName;
data['year_published'] = this.yearPublished;
data['month_published'] = this.monthPublished;
data['week_published'] = this.weekPublished;
return data;
}
}
要將數據分配給它,您可以這樣做:
列出書籍型號= [];
bookModel = 等待 fetchBooks();
為了向您展示您的 fetchBooks() 函數應該如何,可以這樣做:
Future<List<BookModel>> fetchBooks() async {
var result = //Get your json data from Api
List jsonReponse = result.toList();
return jsonReponse.map((book) => new BookModel.fromJson(book)).toList();
}
要訪問該數據,您可以使用 Futurebuilder 或狀態管理解決方案,例如 Provider
Futurebuilder 的示例:
FutureBuilder<List<BookModel>>(
future: fetchBooks(),
builder: (context, AsyncSnapshot<List<BookModel>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return //LoadingWidget
} else {
List<BookModel> bookModelList = snapshot.data;
return Text(bookModelList.books[0].bookId);
}
},
);
使用上面的解決方案,listviewbuilder 是必要的,請記住將 0 替換為 listview 中的索引。
##注意:此解決方案未經測試,應該只是為您指明正確的方向##
此外,如果您的 JsonResponse 包含更多數據,您需要更新模型類。這是生成模型類的有用工具
https://jsontodart.com/
對於您提到的 DateTime 功能,您可能需要像 unix 時間到日期時間轉換一樣將紀元時間轉換為時間戳顫動
在您的 Futurebuilder 列表視圖中,您可以使用行小部件並排顯示
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句