Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart classes for models from JSON (code generation)

I was looking at this thread: https://groups.google.com/a/dartlang.org/forum/#!topic/misc/0pv-Uaq8FGI but still cannot find a solution for what I would like to have on the client side (possible on the server as well).

I imagine there should be a way to provide a standard format for data structure that is represented as JSON object in JS land (for example json schema or yaml or whatever) that could be used as input to generate Dart classes that contain the fromJSON constructor and toJSON method (possible some checks as well for the data ranges) that the developer can then extend if additional logic is needed over the data coming over the wire.

I do not want to use mirrors if possible, instead the classes should be statically generated (i.e. run a tool -> get the class(es) to match the latest schema/input).

Can you point me to the right direction?

Thanks.

like image 366
Peter StJ Avatar asked Jan 03 '15 21:01

Peter StJ


People also ask

Does dart support JSON?

Dart has built in support for parsing json. Given a String you can use the dart:convert library and convert the Json (if valid json) to a Map with string keys and dynamic objects.

Which dart library is used for JSON parsing?

The dart:convert library provides support for JSON. Use HttpRequest to dynamically load data.


1 Answers

There is a great package called json_serializable on pub that creates serializers for your models via code generation.

You can customize the generated code via annotations or you can just modify the generated code by hand.

like image 64
Tobias Marschall Avatar answered Sep 21 '22 10:09

Tobias Marschall