-
Notifications
You must be signed in to change notification settings - Fork 0
Constructor
While JSON is excellent for defining raw data, complex applications often require that data to be instantiated as Class Objects. This allows you to leverage class methods, private logic, and default properties directly from your data files.
To transform a JSON object into a specific class, the class must first be registered in the central registry. This maps the string identifier used in your JSON to the actual class constructor in your code.
import * as RichJson from "@rjson/parser"
class DataModel {
id = 0;
timestamp = Date.now();
}
// Register a single class mapping
RichJson.addClassMapping("DataModel", DataModel);
// Register multiple mappings simultaneously
RichJson.addClassMappings({
"DataModel": DataModel,
"UserProfile": UserProfile
});The system identifies which class to instantiate by looking for specific key prefixes within your JSON structure:
| Type | Syntax | Execution Timing |
|---|---|---|
| Normal | "key=ClassName" |
Instantiated immediately upon the initial data resolution. |
| Late Apply | "key==ClassName" |
Instantiated deferred until a specific lifecycle event or "Late Apply" phase. |
Important
Parameter Constraint: Constructors are called without arguments (e.g., new ClassName()). All property initialization should be handled via class defaults or the data provided within the JSON object itself.
The choice between Normal and Late Apply constructors depends entirely on your data's dependency on the runtime environment:
-
Normal Apply (
=): Best for self-contained data structures (Configuration, Constants, Static UI definitions). These are ready for use as soon as the file is parsed. -
Late Apply (
==): Best for objects that require external context or state that may not be available during the initial loading phase. This ensures the object is only created once its dependencies (such as active environment variables or session data) are fully initialized.
import * as RichJson from "@rjson/parser"
class DataClass() {
name = undefined;
hp = 40;
}
RichJson.addClassMapping("DataClass", DataClass);
{
"some_object=DataClass": {
"name": "Hawkmax"
}
}{
"some_object": {
"name": "Hawkmax",
"hp": 40
}
}Author’s Recommendation: next read Inheritance
Back to Repo ● Wiki Home
Copyright © Maximilian Schwarz