dart_jsona 0.0.1

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

dart_jsona #

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

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.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub 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.4 Jan 13, 2019 Go to the documentation of dart_jsona 0.0.4 Download dart_jsona 0.0.4 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]
18
Health:
Code health derived from static analysis. [more]
30
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
51
Overall:
Weighted score of the above. [more]
28
Learn more about scoring.

We analyzed this package on May 8, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.3.0
  • pana: 0.12.15

Platforms

Detected platforms:

Low code quality prevents platform classification.

Health issues and suggestions

Fix lib/src/builders/model_serializer.dart. (-44.03 points)

Analysis of lib/src/builders/model_serializer.dart failed with 2 errors, 1 hint:

line 94 col 7: Functions can't include return statements both with and without values.

line 131 col 5: Functions can't include return statements both with and without values.

line 58 col 9: Use isNotEmpty instead of length

Fix lib/src/builders/property_mapper.dart. (-44.03 points)

Analysis of lib/src/builders/property_mapper.dart failed with 2 errors, 1 hint:

line 21 col 7: Functions can't include return statements both with and without values.

line 31 col 5: Functions can't include return statements both with and without values.

line 47 col 11: Use contains instead of indexOf

Document public APIs. (-1 points)

9 out of 9 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Fix lib/src/builders/json_deserializer.dart. (-0.50 points)

Analysis of lib/src/builders/json_deserializer.dart reported 1 hint:

line 127 col 9: Use isNotEmpty instead of length

Fix additional 3 files with analysis or formatting issues. (-0.50 points)

Additional issues in the following files:

  • lib/src/builders/util.dart (1 hint)
  • 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 issues and suggestions

Fix platform conflicts. (-20 points)

Low code quality prevents platform classification.

The package description is too short. (-19 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

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

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

Dependencies

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