JSON API parser for Flutter

Overview

Flutter Japx - JSON:API Decoder/Encoder

Japx

Lightweight [JSON:API][1] parser that flattens complex [JSON:API][1] structure and turns it into simple JSON and vice versa. It works by transferring Map<String, dynamic> to Map<String, dynamic>, so you can use json_serializable or any other object mapping tool that you prefer.

Usage

For decoding the API responses use function Japx.decode(Map<String, dynamic> jsonApi, {String includeList}) which returns flattened JSON. Include list is an optional parameter and it is used for deserializing JSON:API relationships.

For encoding use function Japx.encode(Object json, {Map<String, dynamic> additionalParams}) which will return a JSON with JSON:API format.

Decoding

Examples

API response:

{
  "data": {
    "id": "1",
    "type": "users",
    "attributes": {
      "email": "[email protected]",
      "username": "john"
    }
  }

will be transferred to this:

{
  "data": {
    "id": "1",
    "type": "users",
    "email": "[email protected]",
    "username": "john"
  }
}

Advanced examples

Parsing relationship

Response:

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!",
      "body": "The shortest article. Ever.",
      "created": "2015-05-22T14:56:29.000Z",
      "updated": "2015-05-22T14:56:28.000Z"
    },
    "relationships": {
      "author": {
        "data": {"id": "42", "type": "people"}
      }
    }
  }],
  "included": [
    {
      "type": "people",
      "id": "42",
      "attributes": {
        "name": "John",
        "age": 80,
        "gender": "male"
      }
    }
  ]
}

Parsed JSON:

{
  "data": [{
    "type": "articles",
    "id": "1",
    "title": "JSON API paints my bikeshed!",
    "body": "The shortest article. Ever.",
    "created": "2015-05-22T14:56:29.000Z",
    "updated": "2015-05-22T14:56:28.000Z",
    "author": {
      "type": "people",
      "id": "42",
      "name": "John",
      "age": 80,
      "gender": "male"
    }
  }]
}

Decoding additional info

Response:

{
  "data": [
    {
      "type": "articles",
      "id": "3",
      "attributes": {
        "title": "JSON API paints my bikeshed!",
        "body": "The shortest article. Ever.",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z"
      }
    }
  ],
  "meta": {
    "total-pages": 13
  },
  "links": {
    "self": "http://example.com/articles?page[number]=3&page[size]=1",
    "first": "http://example.com/articles?page[number]=1&page[size]=1",
    "prev": "http://example.com/articles?page[number]=2&page[size]=1",
    "next": "http://example.com/articles?page[number]=4&page[size]=1",
    "last": "http://example.com/articles?page[number]=13&page[size]=1"
  },
  "additional": {
    "info": "My custom info"
  }
}

Parsed JSON:

{
  "data": [
    {
      "type": "articles",
      "id": "3",
      "title": "JSON API paints my bikeshed!",
      "body": "The shortest article. Ever.",
      "created": "2015-05-22T14:56:29.000Z",
      "updated": "2015-05-22T14:56:28.000Z"
    }
  ],
  "meta": {
    "total-pages": 13
  },
  "links": {
    "self": "http://example.com/articles?page[number]=3&page[size]=1",
    "first": "http://example.com/articles?page[number]=1&page[size]=1",
    "prev": "http://example.com/articles?page[number]=2&page[size]=1",
    "next": "http://example.com/articles?page[number]=4&page[size]=1",
    "last": "http://example.com/articles?page[number]=13&page[size]=1"
  },
  "additional": {
    "info": "My custom info"
  }
}

Encoding

Examples

Basic encoding

Your JSON:

{
  "type": "articles",
  "email": "[email protected]",
  "password": "password",
  "push_token": "x",
  "uuid": "123"
}

JSON:API:

{
  "data": {
    "type": "articles",
    "attributes": {
      "email": "[email protected]",
      "password": "password",
      "push_token": "x",
      "uuid": "123"
    },
    "relationships": {}
  }
}

Advanced Examples

Recursive encoding

Your JSON:

{
  "type": "articles",
  "id": "1",
  "title": "JSON API paints my bikeshed!",
  "body": "The shortest article. Ever.",
  "created": "2015-05-22T14:56:29.000Z",
  "updated": "2015-05-22T14:56:28.000Z",
  "author": {
    "type": "people",
    "id": "42",
    "name": "John",
    "age": 80,
    "gender": "male",
    "article": {
      "type": "articles",
      "id": "1",
      "title": "JSON API paints my bikeshed!",
      "body": "The shortest article. Ever.",
      "created": "2015-05-22T14:56:29.000Z",
      "updated": "2015-05-22T14:56:28.000Z",
      "author": {
        "type": "people",
        "id": "42",
        "name": "John",
        "age": 80,
        "gender": "male"
      }
    }
  }
}

Encode result:

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!",
      "body": "The shortest article. Ever.",
      "created": "2015-05-22T14:56:29.000Z",
      "updated": "2015-05-22T14:56:28.000Z"
    },
    "relationships": {
      "author": {
        "data": {"id": "42", "type": "people"}
      }
    }
  }
}

Meta encoding

JSON with meta parameter:

{
  "id" : "33",
  "type" : "time_off_request",
  "status" : "approved",
  "start_date" : "2019-01-14",
  "end_date" : "2019-01-31",
  "policy" : [
    { "id": "24", "type": "time_off_policy", "meta": "TOP24" },
    { "id": "25", "type": "time_off_policy", "meta": "TOP25" }
  ],
  "user" : {
    "id" : "25",
    "type" : "user",
    "avatar" : "",
    "email" : "[email protected]",
    "name" : "user name",
    "meta": {
      "meta_user": "meta1",
      "meta_user2": "meta2"
    }
  },
  "meta": [
    { "page": 24 },
    { "offset": 24 }
  ]
}

Result:

{
  "data": {
    "id": "33",
    "type": "time_off_request",
    "attributes": {
      "status": "approved",
      "start_date": "2019-01-14",
      "end_date": "2019-01-31",
      "meta": [
        { "page": 24 },
        { "offset": 24 }
      ]
    },
    "relationships": {
      "user": {
        "data": {
          "id": "25",
          "type": "user"
        }
      },
      "policy": {
        "data": [
          {
            "id": "24",
            "type": "time_off_policy"
          },
          {
            "id": "25",
            "type": "time_off_policy"
          }
        ]
      }
    }
  }
}

Example project

Simple project with mocked API can be found in this repository. Clone the repository, set the main.dart as an application starting point and run the project.

Usage with JsonSerializable

This package can be implemented as a simple layer into your exisiting stack. For example, if you use JsonSerializable, you can do it like this:

@JsonSerializable(nullable: false)
class Article {

  factory Article.fromJson(Map<String, dynamic> json) => _$ArticleFromJson(Japx.decode(json));
  Map<String, dynamic> toJson() => Japx.encode(_$ArticleToJson(this));

Authors

Vlaho Poluta, [email protected]

Maroje Marcelic, [email protected]

Maintained by Infinum

License

Japx is available under the MIT license. See the LICENSE file for more info.

You might also like...

An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Aug 24, 2022

A generator to create config class from json files that support many environments

A generator to create config class from json files that support many environments. Motivation If you use a json file to config your applications, perp

Oct 9, 2021

library to help you create database on local memory, support json local database inspired by lowdb

Licensed Licensed under the MIT License http://opensource.org/licenses/MIT. SPDX-License-Identifier: MIT Copyright (c) 2021 Azkadev http://github.c

Oct 17, 2022

Generates utilities to aid in serializing to/from JSON.

Provides Dart Build System builders for handling JSON. json_serializable Package: https://pub.dev/packages/json_serializable Source code The core pack

Jan 8, 2023

From JSON to Dart Advanced

From JSON to Dart Advanced

From JSON to Dart Advanced Table of Contents Features Convert from clipboard Convert from selection Convert from clipboard to code generation Convert

Dec 17, 2022

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Jan 6, 2023

A simple flexible API wrapper for coinbase commerce API. Totally unofficial.

coinbase_commerce A dart library that connects to interact with the Coinbase Commerce API. Enables projects to connect seamlessly to coinbase and rece

Oct 17, 2021

Converts SVG icons to OTF font and generates Flutter-compatible class. Provides an API and a CLI tool.

Fontify The Fontify package provides an easy way to convert SVG icons to OpenType font and generate Flutter-compatible class that contains identifiers

Oct 28, 2022

An encapsulation made around openrouteservice API for Dart and Flutter projects.

An encapsulation made around openrouteservice API for Dart and Flutter projects.

An encapsulation made around openrouteservice API for Dart and Flutter projects. Made for easy generation of Routes and Directions on Maps, Isochrones, Time-Distance Matrix, Pelias Geocoding, POIs, Elevation and routing Optimizations using their amazing API.

Oct 10, 2022
Comments
  • Decoding ignores relationships in include for compound documents

    Decoding ignores relationships in include for compound documents

    jsonapi-response.txt

    japx is not able to parse the relationships in include. In the example file above the user relationship with comments is not decoded. It seems the included parameter support is not sufficient.

    opened by abhinandan-isha 2
  • Add json serializable example to readme

    Add json serializable example to readme

    I think one big advantage over the other JsonApi package is that this can plug into any stack, so it's good to have that written.

    Can we add this? Is this example I wrote ok?

    opened by itsJoKr 0
  • Array relationships in included relationships are set to null if they are not present

    Array relationships in included relationships are set to null if they are not present

    Array relationships (one-many) that are part of the "included" field have their items set as null when they themselves are not included in the server response. For example:

    {
        {
      "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
          "title": "JSON API paints my bikeshed!",
          "body": "The shortest article. Ever.",
          "created": "2015-05-22T14:56:29.000Z",
          "updated": "2015-05-22T14:56:28.000Z"
        },
        "relationships": {
          "author": {
            "data": {"id": "42", "type": "people"}
          }
        }
      },
      "included": [
        {
          "type": "people",
          "id": "42",
          "attributes": {
            "name": "John",
            "age": 80,
            "gender": "male"
          },
          "relationships": {
            "article": {
              "data": {"id": "1", "type": "articles"}
            },
            "categories" : {
              "data" : [
                {"id": "1", "type": "categories"}
              ]
            }
          }
        }
      ]
    }
    

    Here relationships.article will be correctly parsed and shown, but categories.data will be set to a array with all its items in null (it won't even be an empty array, breaking applications on some server responses).

    The expected output is:

    {
      "data": {
        "type": "articles",
        "id": "1",
        "title": "JSON API paints my bikeshed!",
        "body": "The shortest article. Ever.",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z",
        "author": {
          "type": "people",
          "id": "42",
          ...
          "categories": [
            {
              "type": "categories",
              "id": "1"
            }
          ],
          "article": { ... }
        }
      }
    }
    

    The actual output is

    {
      "data": {
        "type": "articles",
        "id": "1",
        "title": "JSON API paints my bikeshed!",
        "body": "The shortest article. Ever.",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z",
        "author": {
          "type": "people",
          "id": "42",
          ...
          "categories": [
            null
          ],
          "article": { ... }
        }
      }
    }
    

    This is fixed in #19

    opened by nicobritos 0
Releases(v2.0.3)
Owner
Infinum
We're an independent design & development agency of 350 people, creating beautiful software for 16 years.
Infinum
Args simple - A simple argument parser and handler, integrated with JSON and dart

args_simple A simple argument parser and handler, integrated with JSON and dart:

Graciliano Monteiro Passos 1 Jan 22, 2022
Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Kinnara Digital Studio 0 Oct 27, 2021
Dart phone number parser, based on libphonenumber and PhoneNumberKit.

Dart library for parsing phone numbers. Inspired by Google's libphonenumber and PhoneNumberKit for ios.

cedvdb 39 Dec 31, 2022
Dart phone number parser, based on libphonenumber and PhoneNumberKit.

Phone Numbers Parser Dart library for parsing phone numbers. Inspired by Google's libphonenumber and PhoneNumberKit for ios. The advantage of this lib

cedvdb 39 Dec 31, 2022
A Gura parser implementation for Dart

Gura Dart parser This repository contains the implementation of a Gura configuration format parser for Dart, written in pure Dart. (Compliant with spe

Zack Campbell 4 Aug 2, 2021
Parser tool is a real-time compiler and runtime engine for strongly typed PEG parsers

parser_tool Version 0.1.1 (BETA) Parser tool is a real-time compiler and runtime engine for strongly typed PEG parsers. Parser tool contains libraries

null 6 Jun 28, 2021
A CLI tool to help generate dart classes from json returned from API

Json 2 Dart Command line utility Important note There is already a package called json2dart so this package will be called json2dartc ! This project w

Adib Mohsin 38 Oct 5, 2022
Cache json map to local file with Dart:io. Read file with sync api.

local_cache_sync 一个非常简单易用的Flutter本地储存库,适用于在本地储存一列轻量数据(例如用户保存在本地的设备信息,或者缓存一系列用户信息)。 local_cache_sync的所有方法都是同步,而不是异步的。这意味着你不需要使用await就可以获取数据。在flutter中,这

null 16 Jun 24, 2022
A flutter package that allows you to transform your excel to json

excel_to_json A package that allows you to transform your excel to the following format: Excel To JSON Getting Started At current the package allows y

Vitor Amaral de Melo 0 Nov 7, 2022
A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

DotCoder 1 Aug 23, 2022