How it works
As a compiled language, VoltScript can't leverage reflection to convert the data. However, the Execute
function in VoltScript can be leveraged with global variables. A string can be built for the code that needs to be run, and Execute
can perform that code.
This covers the basics of converting strings, numbers, and arrays of strings or numbers. But the framework also provides functionality for more sophisticated deserialization scenarios:
- Classes that require a custom constructor.
- Custom converters to convert to / from specific data types.
- Custom converters that require different property names to JSON labels.
- Custom converters that need to call subs or functions instead of writing directly to properties.
- Ignoring specific labels in the JSON.
Entrypoint
The JsonConversionHelper is the object to use for converting from JSON. The Helper can contain:
- A JsonConstructor from which to create the top-level object (if parsing a single JSON object) or objects (if parsing an array of objects).
- An array of JsonConverters for custom deserialization of elements from the JSON.
- An array of labels to ignore from the JSON.
For deserialization, the labels in the JSON object are iterated. But for serialization, VoltScript can't use reflection to know the properties available. So converters must be passed and mapped to properties or functions. More details are in the How To Guides.
Classes with fromJson / toJson function
If a class has a fromJson()
or a toJson()
function with the correct signature, this will be used instead of iterating elements within the JSON. More details are in the How-to guides.
Tip
When parameters are extracted for custom constructors or custom setters, we cannot identify the data type the method signature expects. When adding the parameter to the custom constructor or custom setter, you can define the default value to use if the JSON object doesn't have that label. But it's not possible to identify the datatype of the variable declaration for the default value - a String is a String, whether it's stored in a String variable or Variant variable. And there are valid use cases where method signatures should accept a Variant of differing datatypes.
So if a JSON object contains a value for a specific label, it will just be passed as-is to the custom constructor or custom setter. It is the developer's responsibility to ensure the JSON value is of a valid datatype, or return the error message and require the user to fix up the data.
Best practice is to validate the JSON object before using VoltScript JSON Converter. You can see that paradigm in practice in loadLogWritersFromJson()
, which calls validateWriterJson()
to validate each LogWriter JSON object. The same approach is also done in VoltScript's dependency management, in archipelago_functions.vss
.