json-to-dart-model
given a json string, this library will generate all the necessary dart classes to parse and generate 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
orjson serializable
thenjson to dart model
generates only types and everything that happens after, thendart 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
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 object separated by commas. 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:
[
{
"__classname": "userpost", // <- 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 "[email protected]".
"title": "json to dart model", // to mark as a default value, change "title" to "[email protected]".
"body": "json to dart advanced..."
}
]
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.
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 [email protected]
or [email protected]
and json to dart model will generate them for you.
[email protected]
– marks as default value.[email protected]
– marks as required value.
{
"[email protected]": 1,
"[email protected]": "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
"[email protected]@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.
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: <latest_version>
dev_dependencies:
# your other dev_dependencies here
build_runner: <latest_version>
json_serializable: <latest_version>
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: <latest_version>
dev_dependencies:
# your other dev_dependencies here
build_runner: <latest_version>
freezed: <latest_version>
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.
@override
bool operator ==(object other) {
if(identical(other, this)) return true;
return other is todos &&
other.userid == userid &&
other.id == id &&
other.title == title &&
other.completed == completed;
}
@override
int get hashcode => userid.hashcode ^ id.hashcode ^ title.hashcode ^ completed.hashcode;
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,
);
}
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 🙂
- read more about flutter’s doc recommendation about json and serialization
how to use
- select a valid json. press
ctrl + shift + p
(linux and mac) orctrl + p
(windows) and search forconvert from selection
orconvert from selection to code generation supported classes
. provide a base class name and location to save. - copy a valid json. press
ctrl + shift + p
(linux and mac) orctrl + p
(windows) and search forconvert from clipboard
orconvert from clipboard to code generation supported classes
. provide a base class name and location to save. - press
ctrl + shift + p
(linux and mac) orctrl + p
(windows) and search foradd code generation libraries to pubspec.yaml
and hit enter. - press
ctrl + shift + p
(linux and mac) orctrl + p
(windows) and search forbuild models
and hit enter. - using short cuts.
- 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
- using key binding on
linux
can throw errorcommand 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
- matches the wrong type. in my experience, some api deliverers write
integer
values instead ofdouble
, 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 hasdouble
andintegers
, the list type returns asnum
. if you write yourself json objects try to give the right value type for better results. it’s all about json quality :sunglasses:
Comments are closed.