You are not logged in.
Pages: 1
Hello everyone,
I am encountering an issue when attempting to use RTTI (Run-Time Type Information) in Delphi to convert a record into a dynamic TDocVariantData. My goal is to loop through all fields or properties of a record and dynamically build a variant structure.
function RecordToDocVariant<T>(const ARecord: T): Variant;
var
Ctx: TRttiContext;
Typ: TRttiType;
Prop: TRttiProperty;
begin
Result := TDocVariantData.New;
Ctx := TRttiContext.Create;
try
Typ := Ctx.GetType(TypeInfo(T)); // Retrieve RTTI for type T
if Typ = nil then
raise Exception.Create('RTTI not available for the type');
for Prop in Typ.GetProperties do
begin
Result.AddValue(Prop.Name, Prop.GetValue(@ARecord).AsVariant);
end;
finally
Ctx.Free;
end;
end;
Example Call
Here’s how I’m calling the function:
var
MyRecord: TMyRecord;
DocVariant: Variant;
begin
MyRecord.ID := 123;
MyRecord.Code := 'ABC123';
DocVariant := RecordToDocVariant<TMyRecord>(MyRecord);
WriteLn(DocVariant.ID);
WriteLn(DocVariant.Code);
end;
Offline
Why are you using the Delphi RTTI?
What is your problem?
The easiest is to use pure mORMot and some in-between JSON.
And use TDocVariantData and not variant late binding.
Edit: Or try https://github.com/synopse/mORMot2/commit/c6cf2db04
Offline
I am trying to find a way to get record values and store them in docVariantData without using serialization/deserialization ?
Last edited by youssef (2025-01-25 10:20:10)
Offline
Pages: 1