json2class 0.0.5
json2class: ^0.0.5 copied to clipboard
A CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.
json2class #
json2class is a CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.
English | 简体中文
Supported Languages #
Currently Supported #
| dart@3 |
Planned Support #
| arkTs | typescript | Other languages to be supported |
Installation #
For JavaScript/TypeScript Frontend Developers #
npx json2class build -h
For Developers Using Other Tech Stacks #
Quick Start #
The tool supports both JSON and JSON5 files.
// ~/projects/test/test.json
{
"test": {
"number": 1,
"string": "test",
"boolean": true,
"arr": ["test"],
"object": { "nextNumber": "" }
}
}
By default, the tool searches for and converts JSON configurations in the current directory where the command is executed.
cd ~/projects/test/
npx json2class build -l dart@3
JSON Configuration Guide #
Class Naming #
// root.json5
{
level1: {
level2: {
test: 1
}
}
}
Class names are generated by concatenating the hierarchical structure. For example, level2 in the above example will generate the following class name:
class rootlevel1level2 extends json2class {
num test = 0;
}
This naming convention may lead to naming conflicts. If a conflict occurs, an error will be thrown during the build process. Changing the JSON file name can avoid such conflicts.
Types #
The value in the JSON configuration is not important, but its type is crucial as it determines the type of the property in the class. Although null is a valid JSON value, if null is configured, the field will be ignored.
{
"test": null
}
The type of an array is determined by its first element. If an empty array is configured, the field will be ignored.
{
"test": []
}
Default Values #
To avoid cumbersome null checks during usage, the generated class properties are assigned default values based on their types.
| Type | Default Value |
|---|---|
| String | '' |
| Boolean | false |
| Number | 0 |
| Array | [] |
| Object | Instance of the object |
If you do not want to set a default value, you can append ? to the JSON field, and the property will be set to null.
{
'test?': 1
}
References #
You can use { "$meta": { "ref": "/filename#/yyy" } } to reference a predefined structure.
By referencing its parent, you can create recursive types.
// filename.json5
{
test: {
t1: 1,
t2: "a",
child: {
"$meta": {
"ref": "/filename#/test"
}
}
}
}
You can also reference a structure from another JSON file.
// filename1.json5
{
test: {
t1: 1,
t2: "a",
}
}
// filename2.json5
{
test: {
t1: 1,
t2: "a",
child: {
"$meta": {
"ref": "/filename1#/test"
}
}
}
}
JSON files can be organized into folders, with a maximum depth of three levels. When referencing, the folder path must be specified.
// ./dir1/filename.json5
{
test: {
t1: 1,
t2: "a",
}
}
// ./dir2/filename.json5
{
test: {
t1: 1,
t2: "a",
child: {
"$meta": {
"ref": "/dir1/filename#/test"
}
}
}
}
Usage of Generated Code #
Core Methods #
| Method Name | Parameters | Return Value | Description |
|---|---|---|---|
| fromJson | Map | Current object | Populates the current object with data from the Map. |
| fromAny | Any value | Current object | Attempts to parse any data into a Map and calls fromJson. |
| fromPreset | - | Current object | Reads preset data from the JSON configuration file and calls fromAny. |
| toJson | - | Map | Converts the current object's data into a Map. |
| toNew | - | New object | Creates a new instance of the current object. |
Data Population Rules #
- DiffType: Input field type mismatch.
| Enum Value | Effect |
|---|---|
| Keep | Retains the original value. |
| Default | Sets the default value. |
| Null | Sets null (required fields are set to default values). |
- MissKey: Input field does not exist.
| Enum Value | Effect |
|---|---|
| Keep | Retains the original value. |
| Default | Sets the default value. |
| Null | Sets null (required fields are set to default values). |
- MoreIndex: Input array length > original array.
| Enum Value | Effect |
|---|---|
| Fill | Inserts based on input values. If types mismatch, sets default value or null based on field optionality. |
| Drop | Discards excess input data, keeping the array length consistent with the original. |
| Null | Fills excess data with null (non-optional fields forced to Null behave like Fill). |
- MissIndex: Input array length < original array.
| Enum Value | Effect |
|---|---|
| Fill | Fills with default values. Multi-dimensional arrays are recursively filled. |
| Drop | Discards excess original data, keeping the array length consistent with the input. |
| Null | Fills excess data with null (non-optional fields forced to Null behave like Fill). |
| Skip | Leaves excess data in the original array unchanged. |
How to Set Rules #
- Global Settings
Json2class.defaultRule.missKey = MissKey.Null;
- Default Global Configuration
| Enum Type | Default Value |
|---|---|
| DiffType | DiffType.Null |
| MissKey | MissKey.Null |
| MoreIndex | MoreIndex.Fill |
| MissIndex | MissIndex.Skip |
- Instance-Level Settings
obj.rule = new Rule();
- Settings for the Current Conversion
Json2class fromAny(dynamic data, {void Function(Rule rule)? setRule, Rule? rule})
Json2class fromJson(dynamic data, {void Function(Rule rule)? setRule, Rule? rule})
Json2class fromPreset({void Function(Rule rule)? setRule, Rule? rule})
Additional Command-Line Options #
-l, --language: Specifies the target language for the build. #
npx json2class build -l dart@3
-s, --search: Specifies the directory to search for JSON configuration files. #
npx json2class build -l dart@3 -s ~/projects/test/
-o, --output: Specifies the output directory for generated files. #
By default, class files are generated in the directory where the JSON configurations are located.
cd ~/projects/test/
npx json2class build -l dart@3 -o ../cache/
Specifying the -o parameter allows you to define an output directory. It is recommended to add this directory or the generated files to .gitignore.
# .gitignore
~/projects/cache/
json2class.*