dart_jsona 0.0.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new48

dart_jsona

pub package

Build Status

It's a ported to dart - Jsona TS

Framework agnostic, customizable library that provide data formatters to simplify work with JSON API v1.0 specification.

This package don't have any dependencies and pretty simple. It used Map<String, dynamic> a lot 😑

It was designed to work with json_serializable

Install

In your pubspec.yaml

dependencies:
    dart_jsona: ^0.0.1

Usage

Deserializer - creates simplified object(s) from json

import 'package:dart_jsona/dart_jsona.dart';

main() {
  Jsona jsona = new Jsona();

  final body = {
    'data': {
      'type': 'town',
      'id': '123',
      'attributes': {
        'name': 'Barcelona',
      },
      'relationships': {
        'country': {
          'data': {
            'type': 'country',
            'id': '32',
          }
        }
      }
    },
    'included': [{
      'type': 'country',
      'id': '32',
      'attributes': {
        'name': 'Spain',
      }
    }]
  };

  final town = jsona.deserialize(body);

  print(town);
  /**
    {
      type: town,
      id: 123,
      name: Barcelona,
      country: {
        type: country,
        id: 32, name: Spain
      },
      relationshipNames: [country]
    }
   */
}

Serializer - creates json from simplified object(s)

import 'package:dart_jsona/dart_jsona.dart';
main() {
    Jsona jsona = new Jsona();

    Map<String dynamic> newJson = jsona.serialize(stuff: town, includedNames: ['country']);

    print(newJson);

    /**
      {
        data: {
        id: 123,
        type: town,
        attributes: {
           name: Barcelona
        },
        relationships: {
          country: {
            data: {
             id: 32, type: country
            }
          }
        }
      },
      included: [{
        id: 32,
        type: country,
        attributes: {
          name: Spain
        }
      }]
    }
    */
}

Deserialize example from https://jsonapi.org/

var jsonApi = {
  "links": {
    "self": "http://example.com/articles",
    "next": "http://example.com/articles?page[offset]=2",
    "last": "http://example.com/articles?page[offset]=10"
  },
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "relationships": {
      "author": {
        "links": {
          "self": "http://example.com/articles/1/relationships/author",
          "related": "http://example.com/articles/1/author"
        },
        "data": { "type": "people", "id": "9" }
      },
      "comments": {
        "links": {
          "self": "http://example.com/articles/1/relationships/comments",
          "related": "http://example.com/articles/1/comments"
        },
        "data": [
          { "type": "comments", "id": "5" },
          { "type": "comments", "id": "12" }
        ]
      }
    },
    "links": {
      "self": "http://example.com/articles/1"
    }
  }],
  "included": [{
    "type": "people",
    "id": "9",
    "attributes": {
      "firstName": "Dan",
      "lastName": "Gebhardt",
      "twitter": "dgeb"
    },
    "links": {
      "self": "http://example.com/people/9"
    }
  }, {
    "type": "comments",
    "id": "5",
    "attributes": {
      "body": "First!"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "2" }
      }
    },
    "links": {
      "self": "http://example.com/comments/5"
    }
  }, {
    "type": "comments",
    "id": "12",
    "attributes": {
      "body": "I like XML better"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "9" }
      }
    },
    "links": {
      "self": "http://example.com/comments/12"
    }
  }]
};

var jsonApiModel = jsona.deserialize(jsonApi);

print(jsonApiModel);

/**
  [
    {
      type: 'articles',
      id: 1,
      title: 'JSON API paints my bikeshed!',
      links: {
        self: 'http://example.com/articles/1'
      },
      author: {
        type: 'people',
        id: 9,
        firstName: 'Dan',
        lastName: 'Gebhardt',
        twitter: 'dgeb',
        links: {
          self: 'http://example.com/people/9'
        }
      },
      comments: [{
        type: 'comments',
        id: 5,
        body: 'First!',
        links: {
          self: 'http://example.com/comments/5'
        },
        author: {
          type: 'people',
          id: 2
        },
        relationshipNames: [author]
      },
      {
        type: 'comments',
        id: 12,
        body: 'I like XML better',
        links: {
          self: 'http://example.com/comments/12'
        },
        author: {
          type: 'people',
          id: 9,
          firstName: 'Dan',
          lastName: 'Gebhardt',
          twitter: 'dgeb',
          links: {
            self: 'http://example.com/people/9'
          }
        },
        relationshipNames: [author]
      }],
      relationshipNames: [author, comments]
    }
  ];
*/

Deserialize in angular service + dart:convert + json_serializable

// post_service.dart

import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart';
import 'package:dart_jsona/dart_jsona.dart';

class PostService {

  static final _postUrl = 'api/posts';
  final Client _http;

  PostService(this._http);

  Future<List<PostModel>> getPosts() async {
    try {
      final response = await _http.get('${apiUrl}/${_postUrl}');

      // create a new post from json
      final posts = (_extractData(response) as List)
          .map((value) => PostModel.fromJson(value))
          .toList();
      return posts;
    } catch(e) {
      throw _handleError(e);
    }
  }

  dynamic _extractData(Response resp) {
    // initialze Jsona
    Jsona jsona = new Jsona();

    // convert to `Map<String, dynamic>` from `String`
    var response = json.decode(resp.body)

    // deserialize response body
    return jsona.deserialize(response);
  }

  Exception _handleError(dynamic e) {
    return Exception('Server error; cause: $e');
  }
}
// post_model.dart

import 'package:json_annotation/json_annotation.dart';

part 'post_model.g.dart';

@JsonSerializable()
class PostModel {
  final String body;
  final String image;
  PostModel(this.body, this.image);

  factory PostModel.fromJson(Map<String, dynamic> json) => _$PostModelFromJson(json);
  Map<String, dynamic> toJson() => _$PostModelToJson(this);
}

Serializer in angular service + + dart:convert + json_serializable

Furute<PostModel> createPost(PostModel data) async {
  try {
    final response = await _http.post('${apiUrl}/posts', body: _decodeRequest(data));

    return PostModel.fromJson(_extractData(response));
  } catch(e) {
    throw _handleError(e);
  }
}

dynamic _decodeRequest(dynamic body) {
  // initialize Jsona
  Jsona jsona = new Jsona();
  body = body.toJson();

  // add type property
  body['type'] = 'post';

  // serialize body
  return json.encode(jsona.serialize(stuff: body));
}

Contributing

Contributing are welcome.

This package on an early stage, and I'll be happy if you fix or create a new feature.

You just need follow these steps:

  • Fork the repo
  • Make new branch
  • Write code magic
  • Write tests
  • Create PR

License

Jsona, examples provided in this repository and in the documentation are MIT licensed.

0.0.1

  • Create Deserializer and Simple Serializer
Jsona jsona = new Jsona();
final town = jsona.deserialize(body);

final newJson = jsona.serialize(stuff: town, includedNames: ['country']);

example/dart_jsona_example.dart

import 'package:dart_jsona/dart_jsona.dart';

void main() {
  Jsona jsona = new Jsona();

  Map<String, dynamic> body = {
    'data': {
      'type': 'town',
      'id': '123',
      'attributes': {
        'name': 'Barcelona',
      },
      'relationships': {
        'country': {
          'data': {
            'type': 'country',
            'id': '32',
          }
        }
      }
    },
    'included': [{
      'type': 'country',
      'id': '32',
      'attributes': {
        'name': 'Spain',
      }
    }]
  };

  final dynamic town = jsona.deserialize(body);

  print(town);
  /**
   * {
   *  type: town,
   *  id: 123,
   *  name: Barcelona,
   *  country: {
   *    type: country,
   *    id: 32, name: Spain
   *  },
   *  relationshipNames: [country]}
   */


  Map<String, Object> jsonBody = jsona.serialize(stuff: town, includeNames: ['country']);

  print(jsonBody);
  /**
   * {
   *   data: {
   *     id: 123,
   *     type: town,
   *     attributes: {
   *       name: Barcelona
   *     },
   *     relationships: {
   *       country: {
   *         data: {
   *           id: 32, type: country
   *         }
   *       }
   *     }
   *   },
   *   included: [{
   *     id: 32,
   *     type: country,
   *     attributes: {
   *       name: Spain
   *     }
   *   }]
   * }
   */
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dart_jsona: ^0.0.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dart_jsona/dart_jsona.dart';
  
Version Uploaded Documentation Archive
0.0.3 Nov 5, 2018 Go to the documentation of dart_jsona 0.0.3 Download dart_jsona 0.0.3 archive
0.0.2 Nov 5, 2018 Go to the documentation of dart_jsona 0.0.2 Download dart_jsona 0.0.2 archive
0.0.1 Nov 5, 2018 Go to the documentation of dart_jsona 0.0.1 Download dart_jsona 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
3
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
48
Learn more about scoring.

We analyzed this package on Nov 14, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.6

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:dart_jsona/dart_jsona.dart.

Health suggestions

Format lib/src/builders/json_deserializer.dart.

Run dartfmt to format lib/src/builders/json_deserializer.dart.

Format lib/src/builders/model_serializer.dart.

Run dartfmt to format lib/src/builders/model_serializer.dart.

Format lib/src/builders/property_mapper.dart.

Run dartfmt to format lib/src/builders/property_mapper.dart.

Fix additional 3 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/builders/util.dart (Run dartfmt to format lib/src/builders/util.dart.)
  • lib/src/dart_jsona_base.dart (Run dartfmt to format lib/src/dart_jsona_base.dart.)
  • lib/src/models/jsona_types.dart (Run dartfmt to format lib/src/models/jsona_types.dart.)

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While there is nothing inherently wrong with versions of 0.0.*, it usually means that the author is still experimenting with the general direction of the API.

The description is too long. (-10 points)

Search engines will display only the first part of the description. Try to keep it under 180 characters.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
Dev dependencies
test ^1.0.0