Serialization and Deserialization
#include <Luna/Runtime/Serialization.hpp>
Luna SDK comes with a built-in serialization and deserialization library that can serialize objects of serializable types to Variant
objects, with can then be encoded to byte streams using JSON or other text and binary formats. One type must meets the following requirements to be a serializable type:
- This type has been registered to the type system.
- This type is marked as serializable by calling
set_serializable
.
set_serializable
accepts one optional SerializableTypeDesc
structure, which let the user set serialization and deserialization callback functions for the type. If this structure is not provided, the default serialization and deserialization procedure will be used. For generic structure types, set_serializable
will be applied to all instanced types of that generic type. The user can also call set_serializable
on one specific instanced type to override the serialization and deserialization behavior set on the generic type.
For any serializable objects, the user can call serialize
to serialize one object to one Variant
, and call deserialize
to deserialize one object from one Variant
.
Default serialization and deserialization behavior
The default serialization procedure checks the type of the object, then returns one Variant
object based on the following rules:
- For structure types, the returned
Variant
will be an object of serializable properties, indexed by their property names. The data of every property is generated by anotherserialize
call. Unserializable properties will be ignored. - For single enumeration types, the returned
Variant
will be the name of the option that matches the underlying value of the object. If no option matches the underlying value, the serialization function will throwBasicError::bad_data
error. - For multiple enumeration types, the returned
Variant
will be an array that contains names of all selected options. If no option is selected, an emptyVariant
array will be returned.
The default deserialization procedure checks the type of the object, then assigns the data of the object based on the following rules:
- For structure types,
deserialize
is called for every serializable property of the object with the data of that property. Properties without data inVariant
and unrecognized properties will be ignored. - For single enumeration types, the default deserialization function reads the name string stored in
Variant
, and assigns the enumeration object with the value whose option name matches the data. If no option matches the name string stored inVariant
, the deserialization function will throwBasicError::bad_data
error. - For multiple enumeration types, the default deserialization function firstly clears the object to
0
, then reads the array of strings stored inVariant
, and sets corresponding bits in the target object. Unrecognized options will be ignored.