ForgeJSONGD
Save and load your Godot classes as JSON in one line each. ForgeJSONGD converts any GDScript or C# class into a JSON dictionary or file (optionally encrypted) and rebuilds it including nested objects, arrays, dictionaries, enums, inheritance, and Godot types like Vector2, Color, and Transform3D. It also validates JSON against your classes or JSON Schema (draft 2020-12), compares JSON data sets, lists differences, and patches JSON objects.
Installation
- Download the addon and copy
addons/ForgeJSONGDinto your Godot project'saddonsfolder. - No plugin activation is required;
ForgeJSONGDis registered as a global class.
Features
- Class to JSON and back:
class_to_json,json_to_class, plus string and file variants. Variables you did not set keep their defaults, unknown keys are ignored. - Files with optional encryption: pass a key to
store_json_file/json_file_to_class. - Inheritance and polymorphism: a child class stored in a parent-typed variable, array or dictionary comes back as the child.
- JSON for web APIs: add
func _forge_plain_json() -> bool: return trueto a data class and the normal functions write and read standard JSON for it, with the field names your API uses (_forge_json_keys). A server can never make a game create classes or load files. - Validate JSON before you load it:
validate_json(data, MyClass)lists every problem with its place (/address/city: expected string, got integer). The class's variable types are the schema, and_forge_schemaadds required fields, ranges, lengths and patterns. Standard JSON Schema, andclass_to_json_schemagives you a class's schema for a server or API docs. - Many types, automatically: numbers, text, enums (saved by name), vectors,
Color,Rect2,AABB,Basis,Quaternion,Transform2D/3D,Plane,Projection, packed arrays,NodePath, typed and untyped arrays and dictionaries, resources,Variant. - Customizable classes: skip variables, pass constructor arguments, or take over saving and loading with optional
_forge_methods. - Safe loading of untrusted files: optionally allow only registered scripts.
- Compare, diff and patch:
check_equal_jsons,compare_jsons_diffandjson_operation(Add,AddDiffer,Replace,Remove,RemoveValue). - GDScript and C#: the same addon serves both languages.
Quick Start (GDScript)
Give your class a class_name so ForgeJSONGD can resolve it when loading:
# player_data.gd
class_name PlayerData
@export var name: String
@export var score: int
var internal_note: String = "Saved by default too"
@export var inventory: Array = []
var player := PlayerData.new()
player.name = "Bob"
player.score = 100
player.inventory = ["Sword", "Potion"]
# Save (creates missing folders; pass a 3rd string argument to encrypt)
ForgeJSONGD.store_json_file("user://player.sav", ForgeJSONGD.class_to_json(player))
# Load
var loaded: PlayerData = ForgeJSONGD.json_file_to_class(PlayerData, "user://player.sav")
print(loaded.name) # Bob
Quick Start (C#)
Tested with Godot 4.7.2 .NET (net8.0). C# classes must be partial, marked [GlobalClass], inherit from GodotObject (RefCounted, Resource, or Node), match their .cs file name, provide a parameterless constructor, and mark saved members with [Export].
// Data.cs
using Godot;
[GlobalClass]
public partial class Data : GodotObject
{
[Export] public string Name { get; set; } = "Default";
[Export] public int Age { get; set; } = 15;
}
var data = new Data { Name = "Ann", Age = 30 };
Forge.StoreJsonFile("user://data.json", Forge.ClassToJson(data));
var loaded = Forge.JsonFileToClass<Data>("user://data.json");
GD.Print(loaded.Name); // Ann
Optional C# Wrapper (Forge.cs)
Copy Forge.cs into your project for strongly-typed calls (or call ResourceLoader.Load<Script>("res://addons/ForgeJSONGD/ForgeJSONGD.gd").Call(...) directly):
using Godot;
using Godot.Collections;
public static class Forge
{
public enum Operation { Add, AddDiffer, Replace, Remove, RemoveValue }
private static string _scriptPath = "res://addons/ForgeJSONGD/ForgeJSONGD.gd";
private static Script _script;
public static string ScriptPath
{
get => _scriptPath;
set { _scriptPath = value; _script = null; }
}
private static Script Addon => _script ??= ResourceLoader.Load<Script>(_scriptPath);
public static Dictionary ClassToJson(GodotObject value, bool specifyClass = false) =>
Addon.Call("class_to_json", value, specifyClass).As<Dictionary>();
public static string ClassToJsonString(GodotObject value, bool specifyClass = false) =>
Addon.Call("class_to_json_string", value, specifyClass).AsString();
public static bool StoreJsonFile(string path, Dictionary data, string securityKey = "") =>
Addon.Call("store_json_file", path, data, securityKey).AsBool();
public static T JsonToClass<[MustBeVariant] T>(Dictionary json) where T : GodotObject, new() =>
Addon.Call("json_to_class", ScriptOf<T>.Value, json).As<T>();
public static T JsonStringToClass<[MustBeVariant] T>(string json) where T : GodotObject, new() =>
Addon.Call("json_string_to_class", ScriptOf<T>.Value, json).As<T>();
public static T JsonFileToClass<[MustBeVariant] T>(string path, string securityKey = "") where T : GodotObject, new() =>
Addon.Call("json_file_to_class", ScriptOf<T>.Value, path, securityKey).As<T>();
public static Dictionary JsonFileToDict(string path, string securityKey = "") =>
Addon.Call("json_file_to_dict", path, securityKey).As<Dictionary>();
public static GodotObject JsonToClass(Dictionary json) =>
Addon.Call("json_to_class", default(Variant), json).As<GodotObject>();
public static bool CheckEqualJsons(Variant first, Variant second) =>
Addon.Call("check_equal_jsons", first, second).AsBool();
public static Dictionary CompareJsonsDiff(Variant first, Variant second) =>
Addon.Call("compare_jsons_diff", first, second).As<Dictionary>();
public static Dictionary JsonOperation(Variant baseJson, Variant referenceJson, Operation operation) =>
Addon.Call("json_operation", baseJson, referenceJson, (int)operation).As<Dictionary>();
public static Array<Dictionary> ValidateJson(Variant json, Variant schema) =>
Addon.Call("validate_json", json, schema).AsGodotArray<Dictionary>();
public static Array<Dictionary> ValidateJson<[MustBeVariant] T>(Variant json) where T : GodotObject, new() =>
Addon.Call("validate_json", json, ScriptOf<T>.Value).AsGodotArray<Dictionary>();
public static Dictionary ClassToJsonSchema<[MustBeVariant] T>() where T : GodotObject, new() =>
Addon.Call("class_to_json_schema", ScriptOf<T>.Value).As<Dictionary>();
public static bool RegisterSchema(Variant schema, string uri = "") =>
Addon.Call("register_schema", schema, uri).AsBool();
public static void ClearRegisteredSchemas() => Addon.Call("clear_registered_schemas");
public static void RegisterScript(Script script) => Addon.Call("register_script", script);
public static void ClearRegisteredScripts() => Addon.Call("clear_registered_scripts");
public static void RegisterScriptAlias(Script script, string alias, bool saveAs = true) =>
Addon.Call("register_script_alias", script, alias, saveAs);
public static void ClearScriptAliases() => Addon.Call("clear_script_aliases");
private static class ScriptOf<T> where T : GodotObject, new()
{
public static readonly Variant Value = Find();
private static Variant Find()
{
var probe = new T();
var script = probe.GetScript();
if (probe is not RefCounted) probe.Free();
return script;
}
}
}
When building C# from the command line, run godot_mono --headless --editor --path . --build-solutions --quit followed by godot_mono --headless --path . --import --quit so Godot registers [GlobalClass] metadata.
Method Reference & Settings
All ForgeJSONGD methods are static. For json_to_class, json_string_to_class, and json_file_to_class, pass a Script (creates a new instance), an existing Object (populates it in place), or null (resolves "script_inheritance" from JSON).
| Method | Purpose |
|---|---|
class_to_json(object, specify_class = false) -> Dictionary |
Object to JSON dictionary (specify_class includes "script_inheritance"). |
class_to_json_string(object, specify_class = false) -> String |
Object to compact JSON string. |
store_json_file(path, data, security_key = "") -> bool |
Writes JSON to file (encrypted if key given); creates missing folders. |
json_to_class(script_or_instance, json) -> Object |
Dictionary to object. |
json_string_to_class(script_or_instance, json_string) -> Object |
JSON string to object (null if invalid JSON). |
json_file_to_class(script_or_instance, path, security_key = "") -> Object |
File to object (returns default instance if file missing/empty). |
json_file_to_dict(path, security_key = "") -> Dictionary |
File to dictionary ({} if missing, invalid, or wrong key). |
convert_array_to_json(array) -> Array |
Converts a standalone Array of values/objects to JSON values. |
convert_dictionary_to_json(dictionary) -> Dictionary |
Converts a standalone Dictionary to JSON entries. |
check_equal_jsons(first, second) -> bool |
Checks if two JSON sources (Dictionary, string, file path, Object) hold equal data. |
compare_jsons_diff(first, second) -> Dictionary |
Returns changed keys as {"key": {"old": a, "new": b}} ({} if equal). |
json_operation(base, reference, operation) -> Dictionary |
Patches base using reference and ForgeJSONGD.Operation. |
validate_json(json, schema) -> Array[Dictionary] |
Validates data against a class or JSON Schema; returns list of errors ([] if valid). |
class_to_json_schema(script) -> Dictionary |
Generates a JSON Schema (draft 2020-12) dictionary from a class. |
register_schema(schema, uri = "") -> bool |
Registers a schema (Dictionary, JSON string, file path, class) for $ref lookup. |
clear_registered_schemas() |
Removes all registered schemas. |
register_script(script) / register_scripts(scripts) |
Restricts dynamic script loading to an allow-list of registered scripts. |
clear_registered_scripts() |
Clears the script allow-list so all scripts are permitted again. |
register_script_alias(script, alias, save_as = true) |
Binds a stable alias to a script so class renames keep loading old saves. |
clear_script_aliases() |
Removes all registered script aliases. |
Global Settings & Constants:
ForgeJSONGD.only_exported_values(defaultfalse): Whentrue, GDScript saves/loads only@exportand@export_storagevariables (C# always saves only[Export]members).ForgeJSONGD.json_indent(default"\t"): File indentation forstore_json_file(""for compact files).ForgeJSONGD.sort_keys(defaulttrue): Sorts JSON keys alphabetically whentrue, or keeps declaration order whenfalse.ForgeJSONGD.SCRIPT_INHERITANCE("script_inheritance"),ForgeJSONGD.CONSTRUCTOR_ARGS("script_constructor_args").
Supported Types, Inheritance & Resources
GDScript saves all script variables by default (including inherited script variables, excluding built-in node properties unless listed in _forge_extra_properties). C# saves [Export] properties and fields. Unset variables keep class defaults; unknown keys are ignored.
| Type | JSON Format & Round-Trip Behavior |
|---|---|
bool, int, float, String (C#: long, byte, double) |
Stored directly. 64-bit integers $\ge 2^{53}$ serialize as exact digit strings so precision is preserved. Whole-number floats in untyped containers use {"forge_float": 5.0} to stay distinct from int. |
enum / @export_enum |
Saved by name ("Angry"), loaded case-insensitively (_ and spaces equivalent) or from integer values. |
Vector2/3/4, Vector2i/3i/4i |
Constructor strings ("Vector2(1, 2)"), or {"x": 1.0, "y": 2.0} in plain HTTP JSON classes. |
Color |
Hex string RRGGBBAA ("ff0000ff"). |
Rect2/2i, AABB, Plane, Quaternion, Basis, Transform2D/3D, Projection |
Constructor strings, restored with exact type even inside Variant and untyped containers. |
PackedByteArray (byte[]) |
Base64 constructor string ("PackedByteArray(\"AQID\")"). |
PackedInt32/64Array, PackedFloat32/64Array, PackedStringArray |
JSON arrays (int[], string[] in C#). |
PackedVector2/3/4Array, PackedColorArray |
Constructor strings (Vector2[] in C#). |
NodePath, StringName |
Plain strings. |
Array, Array[T], Dictionary, Dictionary[K, V] |
JSON arrays/objects. Untyped dictionary keys preserve non-string types (int, float, bool, Vector2) via forge_int: / forge_float: / forge_bool: prefixes. |
Scripted Object / Resource |
Saved inline as a JSON object. File-backed resources outside .tres (e.g., Texture2D) save as their res:// path and reload via ResourceLoader. |
Variant |
Preserves exact runtime type for all supported types and scripted objects. |
Unsupported: Scriptless Object instances (saved as null), Callable, and RID.
Inheritance & Polymorphism
Child instances (Dog) stored in parent-typed properties (Animal), typed collections (Array[Animal], Dictionary[String, Animal]), or untyped containers automatically store "script_inheritance": "Dog" (and "script_uid" for unnamed scripts) and reconstruct as Dog on load. Save with specify_class = true and load with null (ForgeJSONGD.json_to_class(null, json)) to reconstruct without knowing the root type beforehand. If a saved class no longer exists, loading falls back to the declared parent type (or a Dictionary in untyped containers).
Customizing Classes (_forge_* Hooks)
Define any of these optional methods on a GDScript or C# class (in C#, declare them public using exact snake_case names):
| Method | Purpose |
|---|---|
_forge_excluded_properties() -> Array |
Member names to skip during saving and loading. |
_forge_extra_properties() -> Array |
Built-in Godot properties (["position", "rotation", "scale"]) to save and load too. |
_forge_json_keys() -> Dictionary |
Maps class variable names to custom JSON keys ({"user_name": "userName"}). |
_forge_renamed_properties() -> Dictionary |
Maps legacy variable names to current names ({"old_name": "new_name"}) for old saves. |
_forge_plain_json() -> bool |
Return true to read/write standard, marker-free JSON for web APIs. |
_forge_save_by_path() -> bool |
For Resource classes: saves file-backed .tres resources by res:// path instead of inline data. |
_forge_constructor_args() -> Array |
Arguments saved under "script_constructor_args" and passed to _init / constructor on load. |
_forge_schema() -> Dictionary |
Adds JSON Schema rules (required, properties, minimum, pattern, etc.) to the class schema. |
_forge_serialize() -> Dictionary |
Replaces automatic serialization with a custom dictionary. |
_forge_deserialize(json: Dictionary) -> Object |
Custom deserialization (static or instance method in GDScript; public instance method returning GodotObject in C#). |
HTTP APIs & JSON Schema Validation
Standard JSON for Web APIs
Return true from _forge_plain_json() on a DTO class to write and read clean JSON without script_inheritance, forge_float, forge_text:, or forge_resource_path markers. Vectors serialize as {"x": 1.0, "y": 2.0}, Color as hex, and enums by name. Class names and file paths inside incoming server payloads are ignored so external APIs cannot instantiate scripts or load files. In C#, initialize nested object properties (= new()) on plain DTO classes so loading fills the existing object's type.
Validating JSON (validate_json)
ForgeJSONGD.validate_json(json, schema) checks data against a class script or a JSON Schema (draft 2020-12) dictionary, string, or file and returns an Array[Dictionary] of errors ({"path", "keyword", "message", "schema_path"}), or [] when valid:
class_name SignupDto
var user_name: String = ""
var age: int = 0
func _forge_plain_json() -> bool: return true
func _forge_json_keys() -> Dictionary: return {"user_name": "userName"}
func _forge_schema() -> Dictionary:
return {
"required": ["user_name"],
"properties": {
"user_name": {"minLength": 3, "maxLength": 20},
"age": {"minimum": 13},
},
}
var errors := ForgeJSONGD.validate_json('{"userName": "an", "age": 5}', SignupDto)
var schema := ForgeJSONGD.class_to_json_schema(SignupDto) # exportable JSON Schema draft 2020-12
Supports type, enum, const, numeric constraints (minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf), string rules (minLength, maxLength, pattern), array rules (items, prefixItems, minItems, maxItems, uniqueItems, contains, minContains, maxContains), object rules (properties, required, additionalProperties, patternProperties, propertyNames, minProperties, maxProperties, dependentRequired, dependentSchemas), combinators (allOf, anyOf, oneOf, not, if/then/else), and local $ref/$defs/$anchor. External $ref schemas are never fetched over the network; pre-register them via register_schema().
Comparing & Patching JSON
check_equal_jsons, compare_jsons_diff, and json_operation accept any combination of Dictionary, JSON String, file path, or Object without mutating inputs (key order and 1 vs 1.0 are ignored; array order matters):
ForgeJSONGD.Operation.Add: Adds missing keys from reference; combines shared scalar values into[base, ref], appends all array items, and merges dictionaries recursively.ForgeJSONGD.Operation.AddDiffer: LikeAdd, but leaves equal values unchanged and appends only unique array items.ForgeJSONGD.Operation.Replace: Overwrites shared keys with reference values and adds missing keys.ForgeJSONGD.Operation.Remove: Removes all keys present in reference and removes matching array elements.ForgeJSONGD.Operation.RemoveValue: Removes keys/elements only when both key and value match reference.
Security & Memory Notes
- Untrusted Files: Pass a
security_keyto encrypt saves, and register allowed classes (including subclasses) withForgeJSONGD.register_script()before loading shared files so unregistered scripts fall back to the declared base type. - Memory Management:
RefCountedandResourceinstances are freed automatically by Godot. If you loadNodeorGodotObjectclasses, add nodes to the scene tree or callfree()manually when finished.
Changelog for version 5.1.1
2026-11-25 06:42:17
No changelog provided for this version.