
Security News
Microsoft Releases Open Source Toolkit for AI Agent Runtime Security
Microsoft has released an open source toolkit for enforcing runtime security policies on AI agents as adoption accelerates faster than governance controls.
json2class
Advanced tools
json2class is a CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.
English | 简体中文
json2class is a CLI tool to generate class objects from JSON(5), supporting serialization and deserialization.
| dart@3 | arkTs@12 | typescript@5 | kotlin@1.3 | swift@5.7 |
| java | Other languages to be supported |
✅ Recommended Node, npm, and npx Development Environmentnpx 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
Due to the release restrictions of
OpenHarmony Third-party Library Center, from versionv0.0.14, independent executable files are no longer provided. Instead, JS scripts are provided and executed bynode. Fortunately,OpenHarmony Developer ToolsandDevEco-Studiocome withnode. Just add it to thePATHenvironment variable.
OpenHarmony Developer Tools'snodeis usually at: command-line-tools/tool/node/bin/nodeDevEco-Studio'snodeis usually at: DevEco-Studio.app/Contents/tools/node/bin/nodeThe above methods are a bit cumbersome, so it is still recommended to use the npx method for simplicity.
Add the following configuration to oh-package.json5.
{
"scripts": {
"json2class": "node ./oh_modules/json2class/src/main/resources/rawfile/json2class 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. |
| Enum Value | Effect |
|---|---|
| Keep | Retains the original value. |
| Default | Sets the default value. |
| Null | Sets null (required fields are set to default values). |
| Enum Value | Effect |
|---|---|
| Keep | Retains the original value. |
| Default | Sets the default value. |
| Null | Sets null (required fields are set to default values). |
| 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). |
| 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. |
Json2class.defaultRule.missKey = MissKey.Null;
| Enum Type | Default Value |
|---|---|
| DiffType | DiffType.Null |
| MissKey | MissKey.Null |
| MoreIndex | MoreIndex.Fill |
| MissIndex | MissIndex.Skip |
obj.rule = new Rule();
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! 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:
Your feedback is extremely important to us. Thank you very much!
FAQs
json2class is a CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.
We found that json2class demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Microsoft has released an open source toolkit for enforcing runtime security policies on AI agents as adoption accelerates faster than governance controls.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.