GithubHelp home page GithubHelp logo

stablekernel / dart-codable Goto Github PK

View Code? Open in Web Editor NEW
38.0 5.0 8.0 27 KB

A library for converting dynamic, structured data (JSON, YAML) into Dart types.

License: BSD 2-Clause "Simplified" License

Dart 100.00%

dart-codable's Introduction

codable

Build Status

A library for encoding and decoding dynamic data into Dart objects.

Basic Usage

Data objects extend Coding:

class Person extends Coding {
  String name;

  @override
  void decode(KeyedArchive object) {
    // must call super
    super.decode(object);

    name = object.decode("name");   
  }

  @override
  void encode(KeyedArchive object) {
    object.encode("name", name);
  }
}

An object that extends Coding can be read from JSON:

final json = json.decode(...);
final archive = KeyedArchive.unarchive(json);
final person = Person()..decode(archive);

Objects that extend Coding may also be written to JSON:

final person = Person()..name = "Bob";
final archive = KeyedArchive.archive(person);
final json = json.encode(archive);

Coding objects can encode or decode other Coding objects, including lists of Coding objects and maps where Coding objects are values. You must provide a closure that instantiates the Coding object being decoded.

class Team extends Coding {

  List<Person> members;
  Person manager;

  @override
  void decode(KeyedArchive object) {
    super.decode(object); // must call super

    members = object.decodeObjects("members", () => Person());
    manager = object.decodeObject("manager", () => Person());
  }

  @override
  void encode(KeyedArchive object) {
    object.encodeObject("manager", manager);
    object.encodeObjects("members", members);
  }
}

Dynamic Type Casting

Types with primitive type arguments (e.g., List<String> or Map<String, int>) are a particular pain point when decoding. Override castMap in Coding to perform type coercion. You must import package:codable/cast.dart as cast and prefix type names with cast.

import 'package:codable/cast.dart' as cast;
class Container extends Coding {  
  List<String> things;

  @override
  Map<String, cast.Cast<dynamic>> get castMap => {
    "things": cast.List(cast.String)
  };
  

  @override
  void decode(KeyedArchive object) {
    super.decode(object);

    things = object.decode("things");
  }

  @override
  void encode(KeyedArchive object) {
    object.encode("things", things);
  }
}

Document References

Coding objects may be referred to multiple times in a document without duplicating their structure. An object is referenced with the $key key. For example, consider the following JSON:

{
  "components": {
    "thing": {
      "name": "The Thing"
    }    
  },
  "data": {
    "$ref": "#/components/thing"
  }
}

In the above, the decoded value of data inherits all properties from /components/thing:

{
  "$ref": "#/components/thing",
  "name": "The Thing"
}

You may create references in your in-memory data structures through the Coding.referenceURI.

final person = Person()..referenceURI = Uri(path: "/teams/engineering/manager");

The above person is encoded as:

{
  "$ref": "#/teams/engineering/manager"
}

You may have cyclical references.

See the specification for JSON Schema and the $ref keyword for more details.

dart-codable's People

Contributors

joeconwaystk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

dart-codable's Issues

Increase SDK version

I think that the SDK version can be increased to sdk: '>=2.0.0-dev.52.0 <3.0.0' (instead of <2.0.0)

Better handling of enums

Right now it's quite difficult to handle enums properly. We have written our own enum implementations that look like this:

class RecipientType {
  final String id;

  static const to = RecipientType._('to');
  static const cc = RecipientType._('cc');
  static const bcc = RecipientType._('bcc');

  static const values = [to, cc, bcc];

  const RecipientType._(this.id);

  static fromString(String id) => values.firstWhere((type) => type.id == id);
}

Encoding/decoding these values is quite verbose, because you need to check for null values, and then assign the right enum.

It would be great if there was some support for this.

API improvement suggestion: decodeObjects โ†’ decodeObjectList

Cool project! I can see myself using it. One of the things I ran into when testing things was that pesky s.

We have things that look like this:

    members = object.decodeObjects("members", () => Person());
    manager = object.decodeObject("manager", () => Person());

As it turns out, I am a functional analphabet and that extra s to indicate that we are talking about an interable skipped me. I think I would have spotted my error if the indication was much more explicit. Something like object.decodeObjectList

What do you think?

Add a generator?

We've started introducing codable to our codebase, and are rewriting a few API client libraries to use codable. It has become a very repetitive task, and we just thought that a generator would be ideal...

My initial idea is something like this:

  • Create a .json or .yaml file, that defines the properties for each message and its type
  • Define which class is in charge to decode/encode the message

The generator should then add the (camelized) names of the properties to the target class, and write the encode and decode methods for the specified class.

For types that are not native, it should be possible to specify a function that is in charge of en/decoding it.

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.