English | 简体中文
json2class is a CLI tool to generate class objects from JSON(5), supporting serialization and deserialization.
| arkTs@12 | dart@3 | typescript@5 |
| java | kotlin | swift | Other languages to be supported |
npx requires a Node environment. Please install Node first.
npx json2class build -l dart@3
dart pub add dev:json2class
dart run json2class build -l dart@3
Add the following configuration to oh-package.json5.
{
"scripts": {
// Windows system
"json2class": "./oh_modules/json2class/src/main/resources/rawfile/json2class-win.exe build -l arkTs@12",
// macOS system
"json2class": "./oh_modules/json2class/src/main/resources/rawfile/json2class-macos build -l arkTs@12"
}
}
Run the following commands to install.
ohpm install json2class --save-dev
ohpm run json2class
The tool supports both JSON and JSON5 files.
// ~/projects/config/root.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/config/
npx json2class build -l dart@3
Usage of the code
import 'json2class.dart';
main() {
final t = root();
t.fromJson({
'test': {
'number': 123,
'string': 'string',
'boolean': false,
'arr': ['a', 'b', 'c'],
'object': {'nextNumber': ''},
}
});
print(t.test.number);
print(t.test.arr[0]);
print(t.test.object.nextNumber);
print(t.toJson());
}
// 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.
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": []
}
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
}
For an array type, test?
indicates whether the test
property can be set to null
.
The first element in the array denotes the type of the array, and the second element,
if set to null
, marks whether array elements can be set to null
.
{
"test?": ["", null]
}
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"
}
}
}
}
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. |
- DiffType: Handling when the input field type is inconsistent
Enum Value | Effect |
---|---|
Keep | Retains the original value. |
Default | Sets the default value. |
Null | Sets null (required fields are set to default values). |
- MissKey: Handling when the input field is missing
Enum Value | Effect |
---|---|
Keep | Retains the original value. |
Default | Sets the default value. |
Null | Sets null (required fields are set to default values). |
- MoreIndex: Handling when the input array length > original array, determining how to process the extra elements
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: Handling when the input array length < original array, determining how to process the missing elements
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. |
- 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})
npx json2class build -l dart@3
npx json2class build -l dart@3 -s ~/projects/test/
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.*
Thank you for using this tool! In order to quickly improve and release version 1.0.0, we would love to hear your feedback and suggestions. If you encounter any issues or have suggestions for improvement, please feel free to provide feedback through the following channels:
- Submit issues or suggestions on GitHub Issues
- Send an email to Yang Fan<yangfanzn@gmail.com>
Your feedback is extremely important to us. Thank you very much!