json2class 0.0.12 copy "json2class: ^0.0.12" to clipboard
json2class: ^0.0.12 copied to clipboard

A CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.

json2class #

English | 简体中文

json2class is a CLI tool to generate class objects from JSON(5), supporting serialization and deserialization.

Supported Languages #

Currently Supported #

| arkTs@12 | dart@3 | typescript@5 |

Planned Support #

| java | kotlin | swift | Other languages to be supported |

Installation #

npx requires a Node environment. Please install Node first.

npx json2class build -l dart@3
copied to clipboard

Flutter and Dart Development Environment #

dart pub add dev:json2class
dart run json2class build -l dart@3
copied to clipboard

HarmonyOS Development Environment #

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"
  }
}
copied to clipboard

Run the following commands to install.

ohpm install json2class --save-dev
ohpm run json2class
copied to clipboard

Quick Start #

The tool supports both JSON and JSON5 files.

// ~/projects/config/root.json
{
  "test": {
    "number": 1,
    "string": "test",
    "boolean": true,
    "arr": ["test"],
    "object": { "nextNumber": "" }
  }
}
copied to clipboard

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
copied to clipboard

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());
}
copied to clipboard

JSON Configuration Guide #

Class Naming #

// root.json5
{
  "level1": {
    "level2": {
      "test": 1
    }
  }
}
copied to clipboard

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;
}
copied to clipboard

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
}
copied to clipboard

The type of an array is determined by its first element. If an empty array is configured, the field will be ignored.

{
  "test": []
}
copied to clipboard

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
}
copied to clipboard

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]
}
copied to clipboard

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"
      }
    }
  }
}
copied to clipboard

You can also reference a structure from another JSON file.

// filename1.json5
{
  "test": {
    "t1": 1,
    "t2": "a",
  }
}
copied to clipboard
// filename2.json5
{
  "test": {
    "t1": 1,
    "t2": "a",
    "child": {
      "$meta": {
        "ref": "/filename1#/test"
      }
    }
  }
}
copied to clipboard

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",
  }
}
copied to clipboard
// ./dir2/filename.json5
{
  "test": {
    "t1": 1,
    "t2": "a",
    "child": {
      "$meta": {
        "ref": "/dir1/filename#/test"
      }
    }
  }
}
copied to clipboard

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: 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.

How to Set Rules #

  • Global Settings
Json2class.defaultRule.missKey = MissKey.Null;
copied to clipboard
  • 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();
copied to clipboard
  • 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})
copied to clipboard

Additional Command-Line Options #

-l, --language: Specifies the target language for the build. #

npx json2class build -l dart@3
copied to clipboard

-s, --search: Specifies the directory to search for JSON configuration files. #

npx json2class build -l dart@3 -s ~/projects/test/
copied to clipboard

-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/
copied to clipboard

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.*
copied to clipboard

Feedback & Improvement #

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:

Your feedback is extremely important to us. Thank you very much!

2
likes
140
points
130
downloads

Publisher

unverified uploader

Weekly Downloads

2024.09.29 - 2025.04.13

A CLI tool to generate class objects from JSON or JSON5, supporting serialization and deserialization.

Documentation

API reference

License

ISC (license)

Dependencies

path

More

Packages that depend on json2class