I have a json book object which has these nested properties in it:
"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,
},
How can i map this nested json object into datamodel and acces the mapped object's properties? Also how can i combine year_publishedand and month_published into DateTime object and acces it?
CodePudding user response:
you can create a Books Model class which looks like this:
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;
}
}
To Assign data to it you can do that:
List booksModel= [];
booksModel = await fetchBooks();
And to show you how your fetchBooks() function should look like this can be done:
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();
}
To access that data you could use a Futurebuilder or a statemanagment solution such as Provider
an Example for 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);
}
},
);
With the solution above a listviewbuilder is nessecary and remember to replace 0 with index from listview.
##Note: This solution is untested and should just point you in the right direction##
Also if your JsonResponse contains more data you need to update model class. Here is a helpful tool for generating Model classes
https://jsontodart.com/
For the DateTime feature you mentioned you might need to do like an unix time to datetime convertion Convert epoch time into timestamp flutter
In your Futurebuilder listview you can use row widget to show beside each other