Skip to content

JSON serialization

Ravi Teja Gudapati edited this page Jan 9, 2019 · 19 revisions

Decoding JSON request body and writing JSON response are basic tasks of REST APIs. It is for this reason, Jaguar has built-in support for JSON serialization. Context and Response classes provide methods to make JSON serialization easy to use.

Decoding JSON request

Context object provides there methods to decode JSON body from the request:

  1. bodyAsJsonMap Deserializes request body into Dart Map
  2. bodyAsJsonList Deserializes request body into Dart List
  3. bodyAsJson Deserializes request body into a Dart built-in type depending on the body
  server.post('/api/book', (Context ctx) async {
    // Decode request body as JSON Map
    final Map<String, dynamic> json = await ctx.req.bodyAsJsonMap();
    Book book = new Book.fromMap(json);
    // TODO ...
  });

Write JSON Response

The Response class has a json static method that takes a Dart built-in object and returns a Response<String> with mime type set to application/json. It uses JSON.encode internally to encode provided Dart built-in object to JSON string.

  server.post('/api/book', (Context ctx) async {
    Book book;
    // TODO ...
    // Encode Map to JSON
    return Response.json(book.toMap());
  });

What's next?

In this article, we only discussed serializing and deserializing to Dart built-in types.

In the next article, we will learn how to use jaguar_serializer package to serialize any PODO Dart object.

Basics

Serialization

Forms

Sessions

Authentication

  • Basic authentication
  • Form authentication
  • JSON authentication
  • Authorization
  • OAuth

Database

Security

Real time

  • Server sent events (SSE)
  • Websockets

Deployment

  • systemd
  • Docker
  • AppEngine

API Documentation

Clone this wiki locally