- 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.
- C++ Primer習題集(第5版)
- Flutter開發實戰詳解
- Computer Vision for the Web
- Mastering Entity Framework
- Raspberry Pi 2 Server Essentials
- Monitoring Elasticsearch
- OpenCV 3 Blueprints
- Illustrator CS6設計與應用任務教程
- OpenCV Android Programming By Example
- 游戲設計的底層邏輯
- Flutter從0基礎到App上線
- MySQL從入門到精通
- 人件集:人性化的軟件開發
- 精通Oracle 12c 數據庫管理
- JavaScript重難點實例精講