- Dart:Scalable Application Development
- Davy Mitchell Sergey Akopkokhyants Ivo Balbaert
- 572字
- 2021-07-09 18:56:24
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"}, … ]
Serving the JSON
The serving of JSON requires not only the correct type to be specified, but also the security needs to be dealt with for the consumption of this data feed from another web domain:
void _serveJsonFile(HttpRequest request) { request.response ..statusCode = HttpStatus.OK ..headers.set('Content-Type', 'application/json') ..headers.add("Access-Control-Allow-Origin", "*") ..headers.add( "Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS") ..write(hostedBlog.getJSONFeed()) ..close(); }
The content type is set to application/json
, which triggers the XML display in the browser. The access control (CORS) is set to allow any origin and a set of HTTP verbs.
Note
Cross-origin resource sharing (CORS) is a technology that permits restricted resources, such as scripts to be requested from other web domains. For example, a news site wants to request the headlines in the JSON format from a blog to display them.
By default, resources can only be loaded from the same domain. CORS allows specific resources, and actions (HTTP verbs) on those resources such as GET
, POST
, and so on to be shared. So, we may be happy to share our headlines, but not our login validation scripts.
Consuming the JSON feed
JSON has certainly established itself as the modern web data format, being lightweight to both produce and consume. To explore the JSON feature from end to end, we will detour briefly from the server-side and return to the client-side Dart in order to exercise the blog's JSON data feed. For this, take a look at the following code snippet:
Open the example project BlogJsonClient
of this chapter. This a simple web project which acts as a client to the Blog server JSON feed. For this client to operate, the blog server must also be running.
void main() { var jsonSrc = "http://127.0.0.1:8080/feed.json"; HttpRequest.getString(jsonSrc).then((String data) { List decoded = JSON.decode(data); decoded.forEach((post) { querySelector('#output').children.add(new LIElement() ..append(new AnchorElement() ..href = post['url'] ..text = "${post['date']} ${post['title']}")); }); //for }); //then }
The consumer of the JSON feed does not need to be aware of the CORS settings in any way. It simply makes an HTTP request to the appropriate URL to receive the JSON data or other resource. The request must meet the CORS requirements, such as the origin or HTTP verb to receive the desired response. Let's take a look at the following screenshot:

Here, the HttpRequest
class has a static method to return a remote resource as Future<String>
, which is handled asynchronously in the then
clause.
JSON is then iterated and the LI elements (List Items) are added to the DOM structure of the web page.
- Learning Single:page Web Application Development
- 計算思維與算法入門
- Java面向對象思想與程序設計
- C# 2012程序設計實踐教程 (清華電腦學堂)
- Learning ArcGIS Pro 2
- Java游戲服務器架構實戰
- Mastering C# Concurrency
- PHP編程基礎與實例教程
- 微信小程序全棧開發技術與實戰(微課版)
- 快速入門與進階:Creo 4·0全實例精講
- Learning Node.js for .NET Developers
- Webpack實戰:入門、進階與調優(第2版)
- Mastering Concurrency Programming with Java 9(Second Edition)
- HTML并不簡單:Web前端開發精進秘籍
- R語言數據分析從入門到實戰