Book Image

Dart By Example

By : David Mitchell
Book Image

Dart By Example

By: David Mitchell

Overview of this book

Table of Contents (17 chapters)
Dart By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The JSON feed generation


Serving a JSON (JavaScript Object Notation) feed is a useful alternative to XML, as it requires the transfer of less data and is often easier and faster to deal with rather than dealing with XPath. The getJSONfeed method is part of the Blog class, shown as follows:

String getJSONFeed() {
  List posts = new List();
  IDs.forEach((int postID) {
    BlogPost post = getBlogPost(postID);
    Map jsonPost = {};
    jsonPost["id"] = post._id;
    jsonPost["date"] = post._date;
    jsonPost["title"] = post._title;
    jsonPost["url"] = "http://127.0.0.1:8080/post${post._id}.html";
    posts.add(jsonPost);
    });
  return JSON.encode(posts);
}

This method follows the same approach as RSS, with the main data structure being a list this time and the items being entries in that list. The list can be converted to JSON using the JSON.encode method from dart:convert:

[
…
 {"id" : 6,
   "date" : "02/05/2015",
    "title" : "Lemur Facts",
    "url" : "http://127.0.0.1:8080/post6.html...