Selam Girma

Selam Girma

1596709680

Command line tool for generating Dart models from Json file

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

Installation

on pubspec.yaml

dependencies:
  json_to_model: ^1.4.1
  build_runner: ^1.9.0
  json_serializable: ^3.3.0
  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",
  "auth_state": "@enum:verified(2),authenticated(1),guest(0)",
  "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;
  ExamplesUserTypeEnum 
    get examplesUserTypeEnum => _examplesUserTypeEnumValues.map[userType];
    set examplesUserTypeEnum(ExamplesUserTypeEnum value) => userType = _examplesUserTypeEnumValues.reverse[value];
  @JsonKey(name: 'user_type') String userType;
  ExamplesAuthStateEnum 
    get examplesAuthStateEnum => _examplesAuthStateEnumValues.map[authState];
    set examplesAuthStateEnum(ExamplesAuthStateEnum value) => authState = _examplesAuthStateEnumValues.reverse[value];
  @JsonKey(name: 'auth_state') int authState;
  User user;
  bool published;

  factory Examples.fromJson(Map<String,dynamic> json) => _$ExamplesFromJson(json);
  Map<String, dynamic> toJson() => _$ExamplesToJson(this);
}

enum ExamplesUserTypeEnum { Admin, AppUser, Normal }
enum ExamplesAuthStateEnum { Verified, Authenticated, Guest }

final _examplesUserTypeEnumValues = _ExamplesUserTypeEnumConverter({
  'admin': ExamplesUserTypeEnum.Admin,
  'app_user': ExamplesUserTypeEnum.AppUser,
  'normal': ExamplesUserTypeEnum.Normal,
});

final _examplesAuthStateEnumValues = _ExamplesAuthStateEnumConverter({
  2: ExamplesAuthStateEnum.Verified,
  1: ExamplesAuthStateEnum.Authenticated,
  0: ExamplesAuthStateEnum.Guest,
});

class _ExamplesUserTypeEnumConverter<String, O> {
  Map<String, O> map;
  Map<O, String> reverseMap;

  _ExamplesUserTypeEnumConverter(this.map);

  Map<O, String> get reverse => reverseMap ??= map.map((k, v) => MapEntry(v, k));
}

class _ExamplesAuthStateEnumConverter<int, O> {
  Map<int, O> map;
  Map<O, int> reverseMap;

  _ExamplesAuthStateEnumConverter(this.map);

  Map<O, int> get reverse => reverseMap ??= map.map((k, v) => MapEntry(v, k));
}

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.

Description Expression Input (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) -
Enum type with values {...:"@enum:(folowed by enum separated by ',')"} {"@import":"@enum:admin(0),app_user(1),normal(2)"} 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 variable

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](https://github.com/fadhilx/json_to_model/blob/master/lib/core/dart_declaration.dart) 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,
  }) =>  """
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);

}

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

Download Details:

Author: fadhilx

Source Code: https://github.com/fadhilx/json_to_model

#flutter #dart #mobile-apps

What is GEEK

Buddha Community

Command line tool for generating Dart models from Json file

Command Line Tool for Generating Dart Models From Json File

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

inspired by json_model.

based of the json_to_model

Contents

Features

FeatureStatus
Null safety
toJson/fromJson
immutable classes
copyWith generation
clone and deepclone
nested json classes
enum support

Installation

on pubspec.yaml

dev_dependencies:
  json_to_model: ^2.2.0

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

What does this library do

Command line tool to convert .json files into immutable .dart models.

Get started

The command will run through your json files 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 flutter pub run json_to_model.

Examples

Input Consider this files named product.json and employee.json

product.json

{
  "id": "123",
  "caseId?": "123",
  "startDate?": "2020-08-08",
  "endDate?": "2020-10-10",
  "placementDescription?": "Description string"
}

eployee.json

{
  "id": "123",
  "displayName?": "Jan Jansen",
  "@ignore products?": "$[]product"
}

Output This will generate this product.dart and employee.dart

product.dart

import 'package:flutter/foundation.dart';

@immutable
class Product {

  const Product({
    required this.id,
    this.caseId,
    this.startDate,
    this.endDate,
    this.placementDescription,
  });

  final String id;
  final String? caseId;
  final String? startDate;
  final String? endDate;
  final String? placementDescription;

  factory Product.fromJson(Map<String,dynamic> json) => Product(
    id: json['id'] as String,
    caseId: json['caseId'] != null ? json['caseId'] as String : null,
    startDate: json['startDate'] != null ? json['startDate'] as String : null,
    endDate: json['endDate'] != null ? json['endDate'] as String : null,
    placementDescription: json['placementDescription'] != null ? json['placementDescription'] as String : null
  );

  Map<String, dynamic> toJson() => {
    'id': id,
    'caseId': caseId,
    'startDate': startDate,
    'endDate': endDate,
    'placementDescription': placementDescription
  };

  Product clone() => Product(
    id: id,
    caseId: caseId,
    startDate: startDate,
    endDate: endDate,
    placementDescription: placementDescription
  );


  Product copyWith({
    String? id,
    String? caseId,
    String? startDate,
    String? endDate,
    String? placementDescription
  }) => Product(
    id: id ?? this.id,
    caseId: caseId ?? this.caseId,
    startDate: startDate ?? this.startDate,
    endDate: endDate ?? this.endDate,
    placementDescription: placementDescription ?? this.placementDescription,
  );

  @override
  bool operator ==(Object other) => identical(this, other)
    || other is Product && id == other.id && caseId == other.caseId && startDate == other.startDate && endDate == other.endDate && placementDescription == other.placementDescription;

  @override
  int get hashCode => id.hashCode ^ caseId.hashCode ^ startDate.hashCode ^ endDate.hashCode ^ placementDescription.hashCode;
}

eployee.dart

import 'package:flutter/foundation.dart';
import 'product.dart';

@immutable
class Employee {

  const Employee({
    required this.id,
    this.displayName,
    this.products,
  });

  final String id;
  final String? displayName;
  final List<Product>? products;

  factory Employee.fromJson(Map<String,dynamic> json) => Employee(
    id: json['id'] as String,
    displayName: json['displayName'] != null ? json['displayName'] as String : null
  );

  Map<String, dynamic> toJson() => {
    'id': id,
    'displayName': displayName
  };

  Employee clone() => Employee(
    id: id,
    displayName: displayName,
    products: products?.map((e) => e.clone()).toList()
  );


  Employee copyWith({
    String? id,
    String? displayName,
    List<Product>? products
  }) => Employee(
    id: id ?? this.id,
    displayName: displayName ?? this.displayName,
    products: products ?? this.products,
  );

  @override
  bool operator ==(Object other) => identical(this, other)
    || other is Employee && id == other.id
    && displayName == other.displayName
    && products == other.products;

  @override
  int get hashCode => id.hashCode ^
    displayName.hashCode ^
    products.hashCode;
}

Input Consider this file named location.json

{
    "locationId?": 93,
    "locationTypeId?": "1234",
    "updatedAt": "@datetime",
    "name?": "Lunet 10a, Veenendaal",
    "confidential?": false,
    "locationType?": "@enum:INSIDE,OUTSIDE,CLIENT,HOME,ROOM,UNKNOWN",
    "point?": {
        "longitude": 58.1234,
        "latitude": 12.123
    }
}

Output This will generate this location.dart

import 'package:flutter/foundation.dart';

@immutable
class Location {

  const Location({
    this.locationId,
    this.locationTypeId,
    required this.updatedAt,
    this.name,
    this.confidential,
    this.locationType,
    this.point,
  });

  final int? locationId;
  final String? locationTypeId;
  final DateTime updatedAt;
  final String? name;
  final bool? confidential;
  LocationLocationTypeEnum
    get locationLocationTypeEnum => _locationLocationTypeEnumValues.map[locationType]!;
  final String? locationType;
  final Point? point;

  factory Location.fromJson(Map<String,dynamic> json) => Location(
    locationId: json['locationId'] != null ? json['locationId'] as int : null,
    locationTypeId: json['locationTypeId'] != null ? json['locationTypeId'] as String : null,
    updatedAt: DateTime.parse(json['updatedAt'] as String),
    name: json['name'] != null ? json['name'] as String : null,
    confidential: json['confidential'] != null ? json['confidential'] as bool : null,
    locationType: json['locationType'] != null ? json['locationType'] as String : null,
    point: json['point'] != null ? Point.fromJson(json['point'] as Map<String, dynamic>) : null
  );

  Map<String, dynamic> toJson() => {
    'locationId': locationId,
    'locationTypeId': locationTypeId,
    'updatedAt': updatedAt.toIso8601String(),
    'name': name,
    'confidential': confidential,
    'locationType': _locationLocationTypeEnumValues.reverse[locationType],
    'point': point?.toJson()
  };

  Location clone() => Location(
    locationId: locationId,
    locationTypeId: locationTypeId,
    updatedAt: updatedAt,
    name: name,
    confidential: confidential,
    locationType: locationType,
    point: point?.clone()
  );

  Location copyWith({
    int? locationId,
    String? locationTypeId,
    DateTime? updatedAt,
    String? name,
    bool? confidential,
    String? locationType,
    Point? point
  }) => Location(
    locationId: locationId ?? this.locationId,
    locationTypeId: locationTypeId ?? this.locationTypeId,
    updatedAt: updatedAt ?? this.updatedAt,
    name: name ?? this.name,
    confidential: confidential ?? this.confidential,
    locationType: locationType ?? this.locationType,
    point: point ?? this.point,
  );

  @override
  bool operator ==(Object other) => identical(this, other)
    || other is Location && locationId == other.locationId && locationTypeId == other.locationTypeId && updatedAt == other.updatedAt && name == other.name && confidential == other.confidential && locationType == other.locationType && point == other.point;

  @override
  int get hashCode => locationId.hashCode ^ locationTypeId.hashCode ^ updatedAt.hashCode ^ name.hashCode ^ confidential.hashCode ^ locationType.hashCode ^ point.hashCode;
}

enum LocationLocationTypeEnum { INSIDE, OUTSIDE, CLIENT, HOME, ROOM, UNKNOWN }

extension LocationLocationTypeEnumEx on LocationLocationTypeEnum{
  String? get value => _locationLocationTypeEnumValues.reverse[this];
}

final _locationLocationTypeEnumValues = _LocationLocationTypeEnumConverter({
  'INSIDE': LocationLocationTypeEnum.INSIDE,
  'OUTSIDE': LocationLocationTypeEnum.OUTSIDE,
  'CLIENT': LocationLocationTypeEnum.CLIENT,
  'HOME': LocationLocationTypeEnum.HOME,
  'ROOM': LocationLocationTypeEnum.ROOM,
  'UNKNOWN': LocationLocationTypeEnum.UNKNOWN,
});

class _LocationLocationTypeEnumConverter<String, O> {
  final Map<String, O> map;
  Map<O, String>? reverseMap;

  _LocationLocationTypeEnumConverter(this.map);

  Map<O, String> get reverse => reverseMap ??= map.map((k, v) => MapEntry(v, k));
}

@immutable
class Point {

  const Point({
    required this.longitude,
    required this.latitude,
  });

  final double longitude;
  final double latitude;

  factory Point.fromJson(Map<String,dynamic> json) => Point(
    longitude: json['longitude'] as double,
    latitude: json['latitude'] as double
  );

  Map<String, dynamic> toJson() => {
    'longitude': longitude,
    'latitude': latitude
  };

  Point clone() => Point(
    longitude: longitude,
    latitude: latitude
  );


  Point copyWith({
    double? longitude,
    double? latitude
  }) => Point(
    longitude: longitude ?? this.longitude,
    latitude: latitude ?? this.latitude,
  );

  @override
  bool operator ==(Object other) => identical(this, other)
    || other is Point && longitude == other.longitude && latitude == other.latitude;

  @override
  int get hashCode => longitude.hashCode ^ latitude.hashCode;
}

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.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add json_to_model

With Flutter:

 $ flutter pub add json_to_model

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  json_to_model: ^3.0.0

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

Import it

Now in your Dart code, you can use:

import 'package:json_to_model/json_to_model.dart';

Download Details:

Author: fadhilx

Source Code: https://github.com/fadhilx/json_to_model

#json #dart 

sendy patel

sendy patel

1617086469

Online secure password generator

Create a secure password using our generator tool. Help prevent a security threat by getting a strong password today on hackthestuff.com.

#password #strong password generator #password generator #password generator tool #random generator tool #google generator tool

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Selam Girma

Selam Girma

1596709680

Command line tool for generating Dart models from Json file

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

Installation

on pubspec.yaml

dependencies:
  json_to_model: ^1.4.1
  build_runner: ^1.9.0
  json_serializable: ^3.3.0
  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",
  "auth_state": "@enum:verified(2),authenticated(1),guest(0)",
  "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;
  ExamplesUserTypeEnum 
    get examplesUserTypeEnum => _examplesUserTypeEnumValues.map[userType];
    set examplesUserTypeEnum(ExamplesUserTypeEnum value) => userType = _examplesUserTypeEnumValues.reverse[value];
  @JsonKey(name: 'user_type') String userType;
  ExamplesAuthStateEnum 
    get examplesAuthStateEnum => _examplesAuthStateEnumValues.map[authState];
    set examplesAuthStateEnum(ExamplesAuthStateEnum value) => authState = _examplesAuthStateEnumValues.reverse[value];
  @JsonKey(name: 'auth_state') int authState;
  User user;
  bool published;

  factory Examples.fromJson(Map<String,dynamic> json) => _$ExamplesFromJson(json);
  Map<String, dynamic> toJson() => _$ExamplesToJson(this);
}

enum ExamplesUserTypeEnum { Admin, AppUser, Normal }
enum ExamplesAuthStateEnum { Verified, Authenticated, Guest }

final _examplesUserTypeEnumValues = _ExamplesUserTypeEnumConverter({
  'admin': ExamplesUserTypeEnum.Admin,
  'app_user': ExamplesUserTypeEnum.AppUser,
  'normal': ExamplesUserTypeEnum.Normal,
});

final _examplesAuthStateEnumValues = _ExamplesAuthStateEnumConverter({
  2: ExamplesAuthStateEnum.Verified,
  1: ExamplesAuthStateEnum.Authenticated,
  0: ExamplesAuthStateEnum.Guest,
});

class _ExamplesUserTypeEnumConverter<String, O> {
  Map<String, O> map;
  Map<O, String> reverseMap;

  _ExamplesUserTypeEnumConverter(this.map);

  Map<O, String> get reverse => reverseMap ??= map.map((k, v) => MapEntry(v, k));
}

class _ExamplesAuthStateEnumConverter<int, O> {
  Map<int, O> map;
  Map<O, int> reverseMap;

  _ExamplesAuthStateEnumConverter(this.map);

  Map<O, int> get reverse => reverseMap ??= map.map((k, v) => MapEntry(v, k));
}

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.

Description Expression Input (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) -
Enum type with values {...:"@enum:(folowed by enum separated by ',')"} {"@import":"@enum:admin(0),app_user(1),normal(2)"} 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 variable

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](https://github.com/fadhilx/json_to_model/blob/master/lib/core/dart_declaration.dart) 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,
  }) =>  """
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);

}

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

Download Details:

Author: fadhilx

Source Code: https://github.com/fadhilx/json_to_model

#flutter #dart #mobile-apps

Vincent Lab

Vincent Lab

1605178380

How to Create a Command Line (CLI) Tool in Node.js

In this video I will show you how to turn a Node.js application into a command line tool application.

#command line #node.js #cli #command line interface #template generator #node.js cli