json_to_model 1.4.0

  • Readme
  • Changelog
  • Installing
  • 78

json_to_model Pub Version #

Command line tool for generating Dart models (json_serializable) from Json file.

partly inspired by json_model.

Installation #

on pubspec.yaml

dependencies:
  json_to_model: ^1.3.13
  build_runner: ^1.7.4
  json_serializable: ^3.2.5
  json_annotation: ^3.0.1

install using pub get command or if you using dart vscode/android studio, you can use install option.

What?, Why?, How? #

What #

Command line tool to convert .json files into .dart model files and finally will generate .g.dart file(json_serializable)

Why #

Problem

You might have a system or back-end REST app, and you want to build a dart app. you may start create models for your data. but to convert from Dart Map need extra work, so you can use json_serializable, but it just to let you handle data conversion, you still need to type it model by model, what if you have huge system that require huge amount of models. to write it all up might distress you.

Solution

This command line tool let your convert your existing .json files(that you might have) into dart(json_serializable) files

Why not just use the existing command line library json_model instead

The json_model is great, cool structure, but it doesnt have recursive import which the feature that i want, and i want it automatically change variable to camelCase, i could write an issue and PR, but its hard to make a changes as it dont really have a clean code scalable structure, and have comments that i dont understand, and contributors last active on that repo is in June, i dont think i could wait any longer, so i made new one, some of core feature remain the same, but (may be) have a better structure.

How #

it run through your json file and find possible type, variable name, import uri, decorator and class name, and will write it into the templates. Create/copy .json files into ./jsons/(default) on root of your project, and run pub run json_to_model.

Example

{
  "id": 2,
  "title": "Hello Guys!",
  "content": "$content",
  "tags": "$[]tag",
  "user_type": "@enum:admin,app_user,normal",
  "user": "$../user/user",
  "published": true
}

Command:

pub run json_to_model

or

flutter pub run json_to_model

Output

import 'package:json_annotation/json_annotation.dart';

import 'content.dart';
import 'tag.dart';
import '../user/user.dart';

part 'examples.g.dart';

@JsonSerializable()
class Examples {
      Examples();

  int id;
  String title;
  Content content;
  List<Tag> tags;
  String userType;
  UserTypeEnum get userTypeEnum => _userTypeEnumFromString(userType);
  User user;
  bool published;

  factory Examples.fromJson(Map<String,dynamic> json) => _$ExamplesFromJson(json);
  Map<String, dynamic> toJson() => _$ExamplesToJson(this);
  
  UserTypeEnum _UserTypeEnumFromString(String input){
    return UserTypeEnum.values.firstWhere(
        (e) {
          final element = e.toString().toLowerCase().substring(e.toString().indexOf('.') + 1);
          return element == input;
        },
        orElse: () => null,
      );
  }
}

enum UserTypeEnum { Admin, AppUser, Normal }

Contents #

Getting started #

  1. Create a directory jsons(default) at root of your project
  2. Put all or Create json files inside jsons directory
  3. run pub run json_to_model. or flutter packages pub run json_to_model flutter project

Usage #

this package will read .json file, and generate .dart file, asign the type of the value as variable type and key as the variable name.

DescriptionExpressionInput (Example)Output(declaration)Output(import)
declare type depends on the json value{...:any type}{"id": 1, "message":"hello world"},int id;
String message;
-
import model and asign type{...:"$value"}{"auth":"$user"}User auth;import 'user.dart'
import recursively{...:"$../pathto/value"}{"price":"$../product/price"}Price price;import '../product/price.dart'
asign list of type and import (can also be recursive){...:"$[]value"}{"addreses":"$[]address"}List<Address> addreses;import 'address.dart'
use json_annotation @JsonKey{"@JsonKey(...)":...}{"@JsonKey(ignore: true) dynamic": "val"}@JsonKey(ignore: true) dynamic val;-
import other library(input value can be array){"@import":...}{"@import":"package:otherlibrary/otherlibrary.dart"}-import 'package:otherlibrary/otherlibrary.dart'
Datetime type{...:"@datetime"}{"createdAt": "@datetime:2020-02-15T15:47:51.742Z"}DateTime createdAt;-
Enum type{...:"@enum:(folowed by enum separated by ',')"}{"@import":"@enum:admin,app_user,normal"}enum UserTypeEnum { Admin, AppUser, Normal }(include variable declaration)-
write code independentally(experimental){"@_...":...}{"@_ // any code here":",its like an escape to write your own code"}// any code here,its like an escape to write your own code-

Examples #

you can copy json below and generate using pub run json_to_model command

Basic #

Source File

./jsons/user.json

{
  "id": 2,
  "username": "John Doe",
  "blocked": false
}

Generated

./lib/models/user.dart

import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
      User();

  int id;
  String username;
  bool blocked;

  factory User.fromJson(Map<String,dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

After that, json_serializable will automatically genereate .g.dart files

./lib/models/user.g.dart

part of 'user.dart';
User _$UserFromJson(Map<String, dynamic> json) {
  return User()
    ..id = json['id'] as int
    ..username = json['username'] as String
    ..blocked = json['blocked'] as bool;
}

Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'id': instance.id,
      'username': instance.username,
      'blocked': instance.blocked,
    };

Asign Type variable #

you can use $ to specify the value to be Type of variable

Source File

./jsons/user.json

{
  "id": 2,
  "username": "John Doe",
  "blocked": false,
  "addresses": "$address" // prefix $
}

In this case, $address is like telling the generator to import address.dart and asign the titled case Address as it is the type of the variable addresses.

Generated

./lib/models/user.dart

import 'package:json_annotation/json_annotation.dart';
import 'address.dart';  // automatic import
part 'user.g.dart';

@JsonSerializable()
class User {
  User();
  int id;
  String username;
  bool blocked;
  Address addresses;  // $address converted to Address as type
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

Asign List

you can use $[] to specify the value to be List of Type of variable

Source File

./jsons/user.json

{
  "id": 2,
  "username": "John Doe",
  "blocked": false,
  "addresses": "$[]address" // prefix $[]
}

Generated

./lib/models/user.dart

import 'package:json_annotation/json_annotation.dart';
import 'address.dart'; // write address as import
part 'user.g.dart';

@JsonSerializable()
class User {
  User();
  int id;
  String username;
  bool blocked;
  List<Address> addresses; // List of Type
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

json_serializable JsonKey #

you can use @JsonKey in key to specify @JsonKey

Source File

./jsons/cart.json

{
  "@JsonKey(ignore: true) dynamic": "md", //jsonKey alias
  "@JsonKey(name: '+1') int": "loved", //jsonKey alias
  "name": "wendux",
  "age": 20
}

Generated

./lib/models/cart.dart

import 'package:json_annotation/json_annotation.dart';

part 'cart.g.dart';

@JsonSerializable()
class Cart {
      Cart();

  @JsonKey(ignore: true) dynamic md; // jsonKey generated
  @JsonKey(name: '+1') int loved; // jsonKey generated
  String name;
  int age;

  factory Cart.fromJson(Map<String,dynamic> json) => _$CartFromJson(json);
  Map<String, dynamic> toJson() => _$CartToJson(this);
}

Glossary #

Entities:

  • imports import statement strings. Got from .json value with prefix $, suffixed it with .dart interpolate into import '$import';\n.
  • fileName file name. Got from .json value with prefix $, but the non-word caracter(\W) being removed, turn it intoCamelCase()
  • className class name. Basically fileName but turned intoTitleCase().
  • declarations declaration statement strings. basically list of DartDeclaration object and turned it intoString() .
  • enums any statements annotated as @enum will be parsed an added to the generated dart statements.
  • enumConverters to automatically bind the enum string value to the actual enum using a converter #

Template: #

String defaultTemplate({
    imports,
    fileName,
    className,
    declarations,
    enums,
    enumConverters,
  }) =>  """
import 'package:json_annotation/json_annotation.dart';

$imports

part '$fileName.g.dart';

@JsonSerializable()
class $className {
      $className();

  $declarations

  factory $className.fromJson(Map<String,dynamic> json) => _\$${className}FromJson(json);
  Map<String, dynamic> toJson() => _\$${className}ToJson(this);
  
  $enumConverters
}

$enums
""";

for more info read model_template.dart

Support #

I'm open contribution for documentation, bug report, code maintenance, etc. properly submit an issue or send a pull request.

Documentation #

any typos, grammar error, unintended word, or ambiguous meaning. you can PR. or maybe create an issue. this is the one i really need your help

Bug/Error #

any bugs, unintended word comments, confusing variable naming. you can create an issue, but also a PR really appreciated.

Feature request #

any missing feature, cool feature, like prefix json key command, or dynamic changing. you can create an issue, or write a dart extension for it.

Contribute #

if you want to help maintain this library, kindly read Contributing.md.

Or #

you can buy me a coffee:

Donate Now
ToyyibPay
Thanks for your support.

1.0.0 #

  • Initial version, created by Stagehand

1.2.0 #

  • rename directory models to `core

1.3.11 #

  • fix TitleCase error on className

1.3.12 #

  • fix file .g.dart not generated

1.3.13 #

  • Better usage peek on doc

1.4.0 #

  • nested object to map feature
  • datetime and enum object

Use this package as a library

1. Depend on it

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


dependencies:
  json_to_model: ^1.4.0

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:json_to_model/json_to_model.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
65
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]
78
Learn more about scoring.

We analyzed this package on Jul 9, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14

Analysis suggestions

Package not compatible with SDK flutter

Because it is not compatible with any of the supported runtimes: flutter-native, flutter-web

Package not compatible with runtime flutter-native on android

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Package not compatible with runtime flutter-native on ios

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Package not compatible with runtime flutter-native on linux

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Package not compatible with runtime flutter-native on macos

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Package not compatible with runtime flutter-native on windows

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Package not compatible with runtime flutter-web on web

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/core/json_model.dart that imports:
  • package:json_to_model/utils/extensions.dart that imports:
  • package:json_to_model/core/dart_declaration.dart that imports:
  • dart:io

Package not compatible with runtime js

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/core/json_model.dart that imports:
  • package:json_to_model/utils/extensions.dart that imports:
  • package:json_to_model/core/dart_declaration.dart that imports:
  • dart:io

Package not compatible with runtime native-aot

Because:

  • package:json_to_model/json_to_model.dart that imports:
  • package:json_to_model/index.dart that imports:
  • package:json_to_model/utils/build_script.dart that imports:
  • package:build_runner/src/build_script_generate/bootstrap.dart that imports:
  • package:build_runner_core/build_runner_core.dart that imports:
  • package:build_runner_core/src/generate/build_runner.dart that imports:
  • package:build_runner_core/src/generate/build_impl.dart that imports:
  • package:build_runner_core/src/generate/build_definition.dart that imports:
  • package:build_runner_core/src/changes/build_script_updates.dart that imports:
  • dart:mirrors

Health suggestions

Fix lib/utils/extensions.dart. (-0.50 points)

Analysis of lib/utils/extensions.dart reported 1 hint:

line 2 col 8: Unused import: 'package:json_to_model/core/json_model.dart'.

Format lib/core/command.dart.

Run dartfmt to format lib/core/command.dart.

Format lib/core/dart_declaration.dart.

Run dartfmt to format lib/core/dart_declaration.dart.

Format lib/core/model_template.dart.

Run dartfmt to format lib/core/model_template.dart.

Format lib/utils/build_script.dart.

Run dartfmt to format lib/utils/build_script.dart.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (build_runner_core).

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package.

Common filename patterns include main.dart, example.dart, and json_to_model.dart. Packages with multiple examples should provide example/README.md.

For more information see the pub package layout conventions.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
args ^1.5.0 1.6.0
build_runner ^1.9.0 1.10.0
build_runner_core ^5.1.0 5.2.0 6.0.0
expressions ^0.1.5 0.1.5
io ^0.3.4 0.3.4
json_annotation ^3.0.1 3.0.1
json_serializable ^3.3.0 3.3.0
logging ^0.11.4 0.11.4
path ^1.6.0 1.7.0
Transitive dependencies
_fe_analyzer_shared 5.0.0
analyzer 0.39.12
async 2.4.2
build 1.3.0
build_config 0.4.2
build_daemon 2.1.4
build_resolvers 1.3.10
built_collection 4.3.2
built_value 7.1.0
charcode 1.1.3
checked_yaml 1.0.2
code_builder 3.4.0
collection 1.14.13 1.15.0-nullsafety
convert 2.1.1
crypto 2.1.5
csslib 0.16.1
dart_style 1.3.6
fixnum 0.10.11
glob 1.2.0
graphs 0.2.0
html 0.14.0+3
http_multi_server 2.2.0
http_parser 3.1.4
js 0.6.2
matcher 0.12.8
meta 1.2.2 1.3.0-nullsafety
mime 0.9.6+3
node_interop 1.1.1
node_io 1.1.1
package_config 1.9.3
petitparser 3.0.4
pool 1.4.0
pub_semver 1.4.4
pubspec_parse 0.1.5
quiver 2.1.3
shelf 0.7.7
shelf_web_socket 0.2.3
source_gen 0.9.5
source_span 1.7.0
stack_trace 1.9.5
stream_channel 2.0.0
stream_transform 1.2.0
string_scanner 1.0.5
term_glyph 1.1.0
timing 0.1.1+2
typed_data 1.2.0 1.3.0-nullsafety
watcher 0.9.7+15
web_socket_channel 1.1.0
yaml 2.2.1
Dev dependencies
pedantic ^1.9.0 1.9.2
test ^1.14.2