From JSON to Dart Advanced

Overview

JSON to Dart Model

Version Install Download Ask Me Anything Issues License: MIT Effective Dart Style Freezed Json Serializable Null Safety

From JSON to Dart Advanced

Table of Contents
  1. Features
  2. The Syntax
  3. Supported Generators
  4. How to use

Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON in a safe way becouse generator support jsonc and json. Also designed to generate Flutter-friendly model classes following the Flutter's doc recommendation and Effective Dart: Style. Extention supports for both Serializing JSON manually and Serializing JSON using code generation libraries like Freezed and Json Serializable.

Note: when you use Freezed or Json Serializable then Json to Dart Model generates only types and everything that happens after, then Dart Build System builders takes care of the rest and is responsible for generated code.

How it Works

Dart to Json Model Generator creates your JSON object into separate files and thanks to this if similar structures are detected generator will create them into different files and merge them with path (import) no matter how named your objects are. In this way, you can keep your code cleaner and more readable. The pathname in the first will be renamed with the class name added as a prefix to show from which class the objects are. If the names continue to be duplicated then will be marked with the index for infinity renaming.

  • Avoid using file base class names as JSON keys to avoid conflicts and unwanted change of structure names. Note: converting from file Json to Dart Model will help to avoid it.
  • Properties named with funky names (like "!breaks", "|breaks", etc) will produce syntax errors.

Customize

To customize your classes is very easy. If you want fast to create a simple class then just click enter continue to skip all methods. Otherwise, build your own. To generate Freezed class and Json Serializable choose Code Generation. Of course, you can set up your configuration in the Settings/Extensions/JSON To Dart Model

How To Customize

Features

Convert from clipboard to manual model classes

  • Convert JSON you copied into dart model classes.

Convert from selection to manual model classes

  • Convert JSON you selected into dart model classes.

Convert from clipboard to code generation libraries supported model classes

  • Convert JSON you copied into code generation libraries supported model classes. A terminal session runs after conversion to generate the rest parts.

Convert from selection to code generation libraries supported model classes

  • Convert JSON you selected into code generation libraries supported model classes. A terminal session runs after conversion to generate the rest parts.

Convert from file

  • Convert all JSON objects from the file.

Json to Dart Model generator keeps all your JSON objects in the file with the name models.jsonc and allows you to configure your classes according to your preferences. models.jsonc content is a list that contains all of your JSON objects that will later be converted to Dart classes. The jsonc format allows you to comment on your JSON objects to easily find them later or make it easier to explain to your team. To create the models.jsonc file you can run command in the command palette Build Models or use keys binging Shift + Ctrl + Alt + B and you will be asked if you want to create a file, hit Enter to add the file. To configure options for output, go to the Settings/Extensions/JSON To Dart Model

Create file manually. Just add a new file to your app directory my_app/models.jsonc and put all JSON objects to the list separated by commas for multi JSON conversions at once. Note that you add base class names to each object with key "__className": "MyClass", the class name will be removed from the object and used as the root class name for your code syntax. Duplicate class names are not allowed to avoid overwriting the files. Inside your models.jsonc. By adding key __path you can override the default path and navigate your models where you want and how your want in your workspace. File should look like this:

Single JSON conversion

<- The base class name of the object. "__path": "/lib/models/user_post", // <- override default path with a new one by adding '__path' key. "userId": 1, "id": 1, // To mark as required value, change "id" to "r@id". "title": "Json To Dart Model", // To mark as a default value, change "title" to "d@title". "body": "Json to Dart advanced..." }">
{
  "__className": "user_post", // <- The base class name of the object.
  "__path": "/lib/models/user_post", // <- override default path with a new one by adding '__path' key.
  "userId": 1,
  "id": 1, // To mark as required value, change "id" to "r@id".
  "title": "Json To Dart Model", // To mark as a default value, change "title" to "d@title".
  "body": "Json to Dart advanced..."
}

Multiple JSON conversion

[
  {
    "__className": "class_one",
    /* ... */
  },
  {
    "__className": "class_two",
    /* ... */
  }
]

After adding the object and convert to Dart classes just run a command from the command palette or simpler use key binding Shift + Ctrl + Alt + B. If you want to update some class, just delete the class folder from the directory and run again Build Models and Json to Dart Model will generate the missing directory.

Convert From Directory

If you are converting JSON models from the models.jsonc file and it has become too large. Then you can split it inside the /.json_models directory. And generator will read all of them and will convert in the same way as from the models.jsonc. Inside the tracked directory supported files are **.json and **.jsonc the rest will be ignored. Of course, you can use both tracked locations at the same time my_app/models.jsonc and my_app/.json_models the generator track the both locations.

Enhanced File Names

Enhanced file names like user.model.dart can make you code friendly with other converters such as like Hive Object Converter. To create it you just need to separate your class name with a dot and after the dot, everything will be added as an enhancement name. Example: user.model result user.model.dart. Just that.

Context Actions

Convert JSON from the right mouse button context menu.

  • Select any folder and run the available method to start conversion.
  • Select the JSON code inside the file **.json or **.jsonc, click the right mouse button, and run the available method to start conversion.
  • Click the right mouse button on the models.jsonc file, and run the available method to start conversion.

Annotations

It is possible to mark JSON values as default or required. Everything that do you need to do, just add to your JSON key d@ or r@ and Json to Dart Model will generate them for you.

  • d@ - Marks as default value.
  • r@ - Marks as required value.
{
  "r@id": 1,
  "d@title": "Json To Dart Model"
}

Result:

class Example {
  int id;
  String title;

  Example({required this.id, this.title = 'Json To Dart Model'});
  
  // The rest...
}

This also works with Freezed and JSON Serializable, also initializes non-constant values like DateTime if marked as default.

Note: what happens if I use multiple annotations "r@d@key" then the generator will prioritize the default value and generate value as the default since only named parameters without a default value can be with required.

Speed Up Converting

If you work a lot with JSON files and get tired every time customize your models in the command palette. Then you can go to the Settings/Extensions/JSON To Dart Model and set the primary configuration to true. And Json to Dart Model will use settings configuration everywhere and never ask you about input. Just choose any command from the selection or clipboard and pick the directory. Set fast mode to true for faster converting to the default directory.

Avoid dynamic Types

By using Dart with null-safety you can activate in the setting avoid dynamic types and the generator will output from/to types as Map . By following Dart standards, List type will not change because the default list type is dynamic in the Dart language. Also, it has no effect if you generate with code generator libraries because they use dynamic types anyway.

Suffix for from and to

The generator has default Json suffix for from/to methods. It is possible to change the extension settings or override by converting JSON.

JSON Serializable

Add serializing JSON using code generation libraries to pubspec.yaml

structure of the pubspec.yaml

dependencies:
  # Your other regular dependencies here
  json_annotation: 
   

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: 
   
  json_serializable: 
   

Freezed

Freezed supports both old versions to 0.12.7 and new from 0.14.0 and higher. Freezed requires three packages to generate JSON files to Freezed classes with a few clicks.

structure of the pubspec.yaml

 dependencies:
   # Your other regular dependencies here
   freezed_annotation: 
   

 dev_dependencies:
   # Your other dev_dependencies here
   build_runner: 
   
   freezed: 
   

Read more about how to install Freezed.

All generated classes with Freezed will be @immutable and support all methods like copyWith, toString, equality operator==... See example:

@freezed
class Todo with _$Todo {
  factory Todo({
    @JsonKey(name: 'todo_id') int? todoId,
    String? description,
    bool? completed,
  }) = _Todo;

  factory Todo.fromJson(Map<String, dynamic> json) => _$TodoFromJson(json);
}

Freezed generator is useful for those who work daily with coding. All you have to do is upgrade some values and Freezed will take care of the rest. You don't need to worry that you have forgotten to update the parser to some method. More what you can do with Freezed read Freezed documentation.

TIP: If you think that you have too many generated files you can look at tips by Freezed on how to ignore lint warnings on generated files.

Equatable

Equatable is the immutable class with the ability to compare your generated models in a better way. You can check if 2 classes, which are different instances, are equals without a single line of extra code. Of course, you can add toString method and copyWith for a better experience.

class Todo extends Equatable {
  final int? id;
  final String? description;
  final bool? completed;

  const Todo({this.id, this.description, this.completed});

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
        id: json['id'] as int?,
        description: json['description'] as String?,
        completed: json['completed'] as bool?,
      );

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

  // Here will be more methods after your customization.
  // toString();
  // copyWith();

  @override
  List<Object?> get props => [id, description, completed];
}

To add Equatable support you just have to select Equatable equality support when the process of parsing your JSON to Code has started and the extension will take care of setting up the advanced code equality check-in your Dart models.

Equality Operator

If you don't want to install the Equatable package and work with @immutable classes and values then you can add equality operator and customize your class as mutable. With utility from the Dart foundation collections, make equality less boilerplate.

Without null safety

@override
bool operator ==(dynamic other) {
  if(identical(other, this)) return true;
  if (other is! Todos) return false;
  return mapEquals(other.toJson() as Map, toJson());
}

@override
int get hashCode => userId.hashCode ^ id.hashCode ^ title.hashCode ^ completed.hashCode;

With null safety

@override
bool operator ==(Object other) {
  if(identical(other, this)) return true;
  if (other is! Todos) return false;
  return mapEquals(other.toJson(), toJson());
}

//..

To String Method

You can add toString method in your classes to improve the debugging experience.

@override
String toString() {
  return 'Todos(userId: $userId, id: $id, title: $title, completed: $completed)';
}

Equatable can implement toString method including all the given props. If you want that behaviour, just have to select Stringify method when the process of parsing your JSON to Code has started.

@override
bool get stringify => true;

CopyWith Method

copyWith method will make your life easier with @immutable classes. Highly recommended with immutable classes.

Todo copyWith({
  int? id,
  String? description,
  bool? completed,
}) {
  return Todo(
    id: id ?? this.id,
    description: description ?? this.description,
    completed: completed ?? this.completed,
  );
}

Codecs

Enabling codecs will implement fromMap/toMap methods with encode/decode inside the fromJson/toJson methods.

Null Safety

Null-Safety is enabled as default like in Dart language and it will indicate that a variable may have the value null. To disable it, go to the Settings/Extensions/JSON To Dart Model.

Note: make sure your packages also support Dart null safety.

Serializing JSON Using Code Generation Libraries

If you'd like to use Code Generation Libraries from Flutter, first of all, I suggest you add dependencies to the pubspec.yaml file. It also can be done with this extension. You don't need to worry about it 😉 After that, you can convert your JSON to model classes. Then you need to run the flutter pub run build_runner build command to generate the missing code of the models, according to Flutter documentation. Fortunately, the extension automatically opens a new terminal session and runs that command for you, yey 😄

How To Use

  1. Select a valid JSON. Press Ctrl + shift + P (Linux and Mac) or Ctrl + P (Windows) and search for Convert From Selection or Convert From Selection To Code Generation Supported Classes. Provide a Base class name and location to save.

  2. Copy a valid JSON. Press Ctrl + shift + P (Linux and Mac) or Ctrl + P (Windows) and search for Convert From Clipboard or Convert From Clipboard To Code Generation Supported Classes. Provide a Base class name and location to save.

  3. Press Ctrl + shift + P (Linux and mac) or Ctrl + P (Windows) and search for Add Code Generation Libraries To pubspec.yaml and hit enter.

  4. Press Ctrl + shift + P (Linux and Mac) or Ctrl + P (Windows) and search for Build Models and hit enter.

  5. Using short cuts.

  6. Convert from the right mouse button context.

Key Bindings

Convert from Clipboard (Shift + Ctrl + Alt + V)

Convert from Selection (Shift + Ctrl + Alt + S)

Convert from file (Shift + Ctrl + Alt + B)

Convert from Clipboard to Code Generation supported classes (Shift + Ctrl + Alt + G)

Convert from Selection to Code Generation supported classes (Shift + Ctrl + Alt + H)

Converter

  • Array type merging
  • Duplicate type prevention
  • Union types
  • Optional types
  • Array types

Known Issues

  1. Using key binding on Linux can throw error Command failed: xclip -selection clipboard -o it happens when Linux lacks clipboard package. To resolve this error run in the terminal this command to install the missing package.

    sudo apt-get install xclip
  2. Matches the wrong type. In my experience, some API deliverers write integer values instead of double, for example, 1 or 1.00 instead of 1.10. The problem is that this generator does a deep object scan and reads each item to detect the type of value and returns the type as found. But with lists works well, if the list only has double and integers, the list type returns as num. If you write yourself JSON objects try to give the right value type for better results. It’s all about JSON quality 😎

Links

Special Thanks

❤️ Special thanks to Israel Ibarra for adding equatable support.
❤️ Special thanks to Arnas for adding Effective Dart: Styles.
❤️ Special thanks to Ayush P Gupta for fixing bugs.

Support us

If you like this, please give us the and share with your friends. Thank you 💙

License

Distributed under the MIT License. See LICENSE for more information.

Contributors

Comments
  • [BUG] double conversion

    [BUG] double conversion

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    during json conversion of doubles the code does

    double a = json['a'] as double

    in case the double does not contains a .0 the dart assumes is an int and gives error; a better conversion I think would be

    double a = json['a']==null ? null: json['a'].toDouble()

    Expected Behavior

    parse with no error

    Steps To Reproduce

    having a jsonc file with this snippet

    {
          "length": 1450.8,
          "width": 1200.8,
          "volume": 255.8
        }
    

    create the models

    tran try to parse a json like:

    {
          "length": 14,
          "width": 120,
          "volume": 255
        }
    

    Version

    3.3.6
    

    Relevant JSON syntax

    {
          "length": 1450.8,
          "width": 1200.8,
          "volume": 255.8
        }
    

    Anything else?

    No response

    opened by Miamoto-Musashi 24
  • File system provider is not available

    File system provider is not available

    I am getting this error. Is there anything I can do to solve this issue.

    Please select a valid directory
    File system provider for e:%5CProjects%5CRestock%5CClients/lib/ is not available.
    
    opened by ansarizafar 24
  • force key type

    force key type

    would be nice to be able to force property type suppose we have:

    {
    "updated":{},
    "created":{}
    }
    

    this will create 2 useless objects Updated and Created, would be nice instead to tell json2dart to create the corresponding properties in the class as Date objects

    probably to follow the naming pattern can be:

    {
    "updated.date":{},
    "created.date":{},
    "issuer.user": {}
    }
    
    enhancement 
    opened by Miamoto-Musashi 14
  • class reference in generated classes

    class reference in generated classes

    would be nice to have the possibility to put object type in the json

    //   USER
      {
        "__className": "User",
        "key": "110afe06-ec31-4d9b-b933-d9e060c7bcb7",
         ....
        "country": null, <---// want it Country class not String
        ....
      },
    

    only way to have the country not String type is put it as null and use the dynamic type on conversion. Would be nice to have the feature to put the Country object instead...

    using jsonc generation probably we can use some kind of placeholder //@Country@ ?

    just a quick idea

    enhancement 
    opened by Miamoto-Musashi 14
  • Can't generate model classes gets following exception.

    Can't generate model classes gets following exception.

    Command 'Json to Dart: Convert From ClipBoard' resulted in an error (Running the contributed command: 'jsonToDart.fromClipboard' failed.)

    To Reproduce Generate class using clipboard option

    Expected behavior It should generate class normally.

    Screenshots image

    Version 3.2.5

    Json

    {
        "status": true,
        "message": "Cuisines get successfully.",
        "data": {
            "cuisines": [
                {
                    "id": 39,
                    "category_id": 2,
                    "name": "General"
                },
                {
                    "id": 40,
                    "category_id": 2,
                    "name": "Birthday"
                },
                {
                    "id": 41,
                    "category_id": 2,
                    "name": "Love"
                }
            ]
        }
    }
    

    Additional context It was working completely fine but suddenly it just started giving this error.

    opened by zahidshaikh08 13
  • Option to not run build runner after generating JSON to Dart

    Option to not run build runner after generating JSON to Dart

    This extension is awesome and thanks for developing this. I don't like to run build runner instantly for a single time. I prefer to run build runner with watch mode which I am manually doing while working with freezed. So it will be great to have a option to disable build runner after generating JSON to Dart.

    opened by 2shrestha22 12
  • file name with .model.dart

    file name with .model.dart

    I'm using Hive Object Converter to introduce Hive notations into models

    Would be nice to automate the process and have Json to Dart let me decide the output pattern so that the other plugin can find the generated files

    enhancement 
    opened by Miamoto-Musashi 10
  • Make generating models directory optional

    Make generating models directory optional

    When we go into creating different modules in project, everytime I need to delete the extraneous models folder and move the inner files into outer parent. Not everytime one needs to generate models dir. Hence can we have a optional dialog asking to generate models dir?

    opened by apgapg 10
  • [BUG] Duplicate models generated

    [BUG] Duplicate models generated

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    I have the following models declared in my models.jsonc

    {
    		"__className": "create_wallet_address_response",
    		"__path": "/lib/app/modules/deposit_withdraw/data/models/create_wallet_address_response",
    		"status": "success",
    		"data.walletAddress": {
    			"id": "4e252595-d326-4c26-89cc-f23d001ffa4a",
    			"account_id": "348e961f-899f-4790-b8e8-712616b74614",
    			"address": "1Msn2kMzveVCgX7i1ZpJWHGnEmNP7LBBL1",
    			"coin": "BTC"
    		}
    	},
    {
    		"__className": "wallet_addresses_response",
    		"__path": "/lib/app/modules/deposit_withdraw/data/models/wallet_addresses_response",
    		"status": "success",
    		"data.walletAddress": [
    			{
    				"id": "4e252595-d326-4c26-89cc-f23d001ffa4a",
    				"account_id": "348e961f-899f-4790-b8e8-712616b74614",
    				"address": "1Msn2kMzveVCgX7i1ZpJWHGnEmNP7LBBL1",
    				"coin": "BTC"
    			}
    		]
    	}
    

    After building models, the data.walletAddress class is generated twice, even though its the exact same model.

    Expected Behavior

    Since the same model is declared twice, build only the first and reference it in the other.

    Steps To Reproduce

    No response

    Version

    3.3.9
    

    Relevant JSON syntax

    No response

    Anything else?

    No response

    opened by Prn-Ice 8
  • how can i custom the class's property name?

    how can i custom the class's property name?

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    models.jsonc file: [ { "__className": "history", "e_id": "9403" } ] history.dart file: class History { String? eId;

    History({this.eId});

    factory History.fromJson(Map<String, dynamic> json) => History( eId: json['e_id'] as String?, );

    Map<String, dynamic> toJson() => { 'e_id': eId, }; }

    Expected Behavior

    how can i annotation the e_id in JSON, auto change the dart class's eId to historyId? like: d@ - Marks as default value. r@ - Marks as required value. hope add the n@field@propery - Marks custom propery name.

    Steps To Reproduce

    No response

    Version

    No response

    Relevant JSON syntax

    No response

    Anything else?

    No response

    question 
    opened by hiyangjx 7
  • [BUG] <Command failed: cscript /Nologo c:\Users\\.vscode\extensions\hirantha.json-to-dart-3.5.0\node_modul>

    [BUG]

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    No response

    Expected Behavior

    Generate JSON to dart class from JSON file.

    Steps To Reproduce

    No response

    Version

    v3.5.3
    

    Relevant JSON syntax

    {
        "status": 200,
        "message": "Profile Updated Successfully.",
        "response": {
            "help_intro": 1
        }
    }
    

    Anything else?

    No response

    opened by anilghimire133 7
  • Bump qs from 6.10.1 to 6.11.0

    Bump qs from 6.10.1 to 6.11.0

    Bumps qs from 6.10.1 to 6.11.0.

    Changelog

    Sourced from qs's changelog.

    6.11.0

    • [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option (#442)
    • [readme] fix version badge

    6.10.5

    • [Fix] stringify: with arrayFormat: comma, properly include an explicit [] on a single-item array (#434)

    6.10.4

    • [Fix] stringify: with arrayFormat: comma, include an explicit [] on a single-item array (#441)
    • [meta] use npmignore to autogenerate an npmignore file
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, object-inspect, tape

    6.10.3

    • [Fix] parse: ignore __proto__ keys (#428)
    • [Robustness] stringify: avoid relying on a global undefined (#427)
    • [actions] reuse common workflows
    • [Dev Deps] update eslint, @ljharb/eslint-config, object-inspect, tape

    6.10.2

    • [Fix] stringify: actually fix cyclic references (#426)
    • [Fix] stringify: avoid encoding arrayformat comma when encodeValuesOnly = true (#424)
    • [readme] remove travis badge; add github actions/codecov badges; update URLs
    • [Docs] add note and links for coercing primitive values (#408)
    • [actions] update codecov uploader
    • [actions] update workflows
    • [Tests] clean up stringify tests slightly
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, object-inspect, safe-publish-latest, tape
    Commits
    • 56763c1 v6.11.0
    • ddd3e29 [readme] fix version badge
    • c313472 [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option
    • 95bc018 v6.10.5
    • 0e903c0 [Fix] stringify: with arrayFormat: comma, properly include an explicit `[...
    • ba9703c v6.10.4
    • 4e44019 [Fix] stringify: with arrayFormat: comma, include an explicit [] on a s...
    • 113b990 [Dev Deps] update object-inspect
    • c77f38f [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, tape
    • 2cf45b2 [meta] use npmignore to autogenerate an npmignore file
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Only make properties optional when needed

    Only make properties optional when needed

    Hello, Is there a way to only mark properties as optional when it finds that the value is missing in one instance (like in a list), and otherwise make the property required?

    opened by DanielSmith1239 0
  • [BUG] Class name problem if have same value in JSON (for example value 'list')

    [BUG] Class name problem if have same value in JSON (for example value 'list')

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    First problem - when I try to convert JSON to dart model, I have a problem with class name, because one of JSON value is 'list' and plugin create a class with name 'List' that cannot work screen

    Second problem its a name of main class of converting JSON, for example I want to call it Weather, but in my JSON have a value 'weather' so when plugin create model files it creates only one file weather.dart and it misses create class weather from JSON value 'weather' weather

    Expected Behavior

    To fix first problem plugin must check if value inside JSON is named already in dart like 'list' so create class with name "WeatherList" like "name_main_class+name_of_json_value" forecast

    To fix second problem plugin must check if value inside JSON is named like the main class like 'weather' so rename to create both files of classes classes

    Steps To Reproduce

    1. copy JSON from https://api.openweathermap.org/data/2.5/forecast/daily?lat=44.34&lon=10.99&cnt=7&appid=1369dd6b5ae78fc9952261ab9aa236b4
    2. paste it in VS Code JSON to dart model
    3. name main class 'Weather' and see this 2 errors
    4. fix it and update plugin
    5. be thankful from community :-)

    Version

    Json to Dart Model v3.5.8 (VS Code 1.72.2)
    Flutter 3.3.4
    Dart 2.18.2
    

    Relevant JSON syntax

    {"city":{"id":3163858,"name":"Zocca","coord":{"lon":10.99,"lat":44.34},"country":"IT","population":4593,"timezone":7200},"cod":"200","message":15.0402978,"cnt":7,"list":[{"dt":1665658800,"sunrise":1665638877,"sunset":1665678982,"temp":{"day":290.56,"min":282.53,"max":290.98,"night":284.53,"eve":288.15,"morn":282.53},"feels_like":{"day":289.84,"night":283.68,"eve":287.43,"morn":282.53},"pressure":1020,"humidity":57,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":2.57,"deg":45,"gust":2.53,"clouds":30,"pop":0.03},{"dt":1665745200,"sunrise":1665725353,"sunset":1665765278,"temp":{"day":290.64,"min":282.43,"max":291.11,"night":283.91,"eve":285.76,"morn":282.43},"feels_like":{"day":289.8,"night":283.1,"eve":284.98,"morn":282.12},"pressure":1018,"humidity":52,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":2.4,"deg":28,"gust":1.73,"clouds":39,"pop":0},{"dt":1665831600,"sunrise":1665811828,"sunset":1665851575,"temp":{"day":292.55,"min":282.66,"max":292.55,"night":284.87,"eve":286.2,"morn":282.66},"feels_like":{"day":291.72,"night":284.11,"eve":285.39,"morn":282.66},"pressure":1016,"humidity":45,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":2.07,"deg":48,"gust":1.93,"clouds":4,"pop":0},{"dt":1665918000,"sunrise":1665898304,"sunset":1665937872,"temp":{"day":292.12,"min":283.55,"max":292.12,"night":284.89,"eve":285.88,"morn":283.55},"feels_like":{"day":291.35,"night":284.23,"eve":285.22,"morn":282.71},"pressure":1021,"humidity":49,"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"speed":1.81,"deg":221,"gust":1.68,"clouds":86,"pop":0},{"dt":1666004400,"sunrise":1665984780,"sunset":1666024171,"temp":{"day":293.02,"min":283.76,"max":293.02,"night":285.51,"eve":286.19,"morn":283.81},"feels_like":{"day":292.34,"night":284.89,"eve":285.59,"morn":283.12},"pressure":1027,"humidity":49,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":1.89,"deg":44,"gust":1.85,"clouds":80,"pop":0},{"dt":1666090800,"sunrise":1666071257,"sunset":1666110471,"temp":{"day":293.38,"min":284.29,"max":293.38,"night":285.82,"eve":286.79,"morn":284.29},"feels_like":{"day":292.71,"night":285.23,"eve":286.19,"morn":283.68},"pressure":1026,"humidity":48,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":1.89,"deg":31,"gust":1.7,"clouds":29,"pop":0},{"dt":1666177200,"sunrise":1666157734,"sunset":1666196771,"temp":{"day":293.37,"min":284.25,"max":293.37,"night":285.81,"eve":286.69,"morn":284.25},"feels_like":{"day":292.65,"night":285.04,"eve":285.95,"morn":283.64},"pressure":1020,"humidity":46,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":2.14,"deg":15,"gust":1.76,"clouds":4,"pop":0}]}
    

    Anything else?

    No response

    bug 
    opened by davaidev 2
  • Target folder persists to be incorrect

    Target folder persists to be incorrect

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    Defining my target folder like this image However persists to generate into /lib/data image

    Expected Behavior

    No response

    Steps To Reproduce

    No response

    Version

    No response

    Relevant JSON syntax

    {
      "__className": "biology",
      "Description": "Basic Biology Multiple Choice Questions (MCQ) to practice basic Biology quiz answers",
      "id": "ppr004",
      "image_url": "",
      "questions": [
        {
          "__className": "question",
          "answers": [
            {
              "__className": "answer",
              "Answer": "Symbiosis",
              "identifier": "A"
            },
            {
              "__className": "answer",
              "Answer": "Mutualism",
              "identifier": "B"
            },
            {
              "__className": "answer",
              "Answer": "Parasitism",
              "identifier": "C"
            },
            {
              "__className": "answer",
              "Answer": "Predation",
              "identifier": "D"
            }
          ],
          "correct_answer": "D",
          "id": "ppr004q001",
          "question": "A relationship in which one animal hunts, kills and eats another"
        }
      ],
      "time_seconds": 900,
      "title": "Biology"
    }
    

    Anything else?

    No response

    opened by nicolasmol 1
  • Support Map type

    Support Map type

    It would be great if Json-to-Dart-Model supported Map data type as it already supported List. Currrently, if the key is something like "key.Map":{}, it creates a whole new class called Map. I think it should use the existed Map class of Dart. Thank you.

    enhancement 
    opened by princ3od 6
Releases(v3.5.8)
Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data

Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data. Javascript / iOS glue framework

glassfy 8 Oct 31, 2022
A CLI tool to help generate dart classes from json returned from API

Json 2 Dart Command line utility Important note There is already a package called json2dart so this package will be called json2dartc ! This project w

Adib Mohsin 38 Oct 5, 2022
An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Leynier Gutiérrez González 7 Aug 24, 2022
Cache json map to local file with Dart:io. Read file with sync api.

local_cache_sync 一个非常简单易用的Flutter本地储存库,适用于在本地储存一列轻量数据(例如用户保存在本地的设备信息,或者缓存一系列用户信息)。 local_cache_sync的所有方法都是同步,而不是异步的。这意味着你不需要使用await就可以获取数据。在flutter中,这

null 16 Jun 24, 2022
Args simple - A simple argument parser and handler, integrated with JSON and dart

args_simple A simple argument parser and handler, integrated with JSON and dart:

Graciliano Monteiro Passos 1 Jan 22, 2022
This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Alexander Mazuruk 356 Jan 6, 2023
A generator to create config class from json files that support many environments

A generator to create config class from json files that support many environments. Motivation If you use a json file to config your applications, perp

Diego Cardenas 0 Oct 9, 2021
A flutter package that allows you to transform your excel to json

excel_to_json A package that allows you to transform your excel to the following format: Excel To JSON Getting Started At current the package allows y

Vitor Amaral de Melo 0 Nov 7, 2022
JSON API parser for Flutter

Flutter Japx - JSON:API Decoder/Encoder Lightweight [JSON:API][1] parser that flattens complex [JSON:API][1] structure and turns it into simple JSON a

Infinum 23 Dec 20, 2022
library to help you create database on local memory, support json local database inspired by lowdb

Licensed Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2021 Azkadev <http://github.c

Azka Full Snack Developer:) 35 Oct 17, 2022
A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

DotCoder 1 Aug 23, 2022
Generates utilities to aid in serializing to/from JSON.

Provides Dart Build System builders for handling JSON. json_serializable Package: https://pub.dev/packages/json_serializable Source code The core pack

Google 1.4k Jan 8, 2023
A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

Julien Scholz 10 Oct 26, 2022
Dart wrapper via dart:ffi for https://github.com/libusb/libusb

libusb Dart wrapper via dart:ffi for https://github.com/libusb/libusb Environment Windows(10) macOS Linux(Ubuntu 18.04 LTS) Usage Checkout example Fea

Woodemi Co., Ltd 28 Dec 20, 2022
Extensible Dart interpreter for Dart with full interop

dart_eval is an extensible interpreter for the Dart language, written in Dart. It's powered under the hood by the Dart analyzer, so it achieves 100% c

Ethan 169 Dec 28, 2022
Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Google 905 Jan 2, 2023
AOP for Flutter(Dart)

AspectD Salute to AspectJ. AspectD is an AOP(aspect oriented programming) framework for dart. Like other traditional aop framework, AspectD provides c

null 1k Jan 7, 2023
Environment specific config generator for Dart and Flutter applications during CI/CD builds

Environment Config Generator Environment specific config generator. Allows to specify env configuration during CI/CD build. Primarily created to simpl

Denis Beketsky 86 Dec 2, 2022
A Very Good Command Line Interface for Dart created by Very Good Ventures 🦄

Very Good CLI Developed with ?? by Very Good Ventures ?? A Very Good Command Line Interface for Dart. Installing $ dart pub global activate very_good_

Very Good Open Source 1.8k Jan 8, 2023