Serialization
Elements provides a platform and language-independent infrastructure for encoding classes and structs for serialization and decoding serialized versions back into instances. The most common scenario for this is to save out the contents of objects to Json or Xml, and reading it back.
Codable Types
A custom type is marked as Codable by attaching the Encodable
, Decodable
or Codable
aspect, defined in the RemObjects.Elements.Serialization.dll
Cirrus assembly. The aspects will generate an implementation for IEncodable
and IDecodable
respectively that covers all properties that are Codable themselves, and not marked to be excluded from ending via [Encode(false)]
.
Simple type (numbers, Chars, Strings, DateTimes, Guids) and some basic collection and array types are also considered codable by defau;t.
Individual properties can optionally be marked with the Encode
aspect with a string parameter, to override the name/key they will be encoded under. This is useful for mapping a type to an existing JSON or XML format that does not exactly match the local spelling convention (for example, camelCase vs PascalCase or underscored).
Individual properties can be excluded from coding by marking them with the same Encode
aspect, but with Boolean false
as a parameter.
Alternatively, a type can of course implement one or both of these interfaces manually. This is useful if a type's structure is vastly different from its encoded representation, or for collection types not supported natively.
type
ICodable = public IEncodable and IDecodable;
IEncodable = public interface
method Encode(aCoder: Coder);
end;
IDecodable = public interface
method Decode(aCoder: Coder);
end;
Encoders and Decoders
A codable type or tree of codable typs can be encoded or decoded using any Encoder
or Decoder
class. Elements RTL provides encoders for Json and Xml formats, and custom encoders can be implemented by anyone, simply by creating a class that implements the IEncoder
or IDedocer
interface, defined in Elements RTL.
var lJsonDecoder := new JsonDecoder();
var lUserData := lJsonDecoder.Decode<UserData>(json);