Search code examples
delphimormot

Change Variant property-names (Delphi)


I'm learning a great framework mORMot for Delphi, and I found plenty of useful functions to handle with Variant (in SynCommons).

Now I want to change some property-names of a Variant, but after a search I have not found such a function, so I decide to write one:

program Project7;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, SynCommons;

function VariantChangeNames(var V: Variant; const FromNames, ToNames: TRawUTF8DynArray): Boolean;
var
  Name: RawUTF8;
  PData: PDocVariantData;
  Val: Variant;
  i, k: Integer;
begin
  Result := False;
  PData := DocVariantData(V);
  i := 0;
  for Name in FromNames do
  begin
    k := PData^.GetValueIndex(Name);
    if k <> -1 then
    begin
      Val := PData^.Value[k];
      PData^.Value[ToNames[i]] := Val;
      PData^.Delete(k); // If delete before setting value, Val will be incorrect.
      Result := True;
    end;
    Inc(i);
  end;
end;

var
  V: Variant;
begin
  V := TDocVariant.New();
  V.Name := 'John';
  V.Age := 20;
  VariantChangeNames(V, ['Name'], ['RealName']);
  Writeln(VariantToString(V)); // {"Age":20,"RealName":"John"}
end.

VariantChangeNames I wrote may not be very efficient since it needs to do both delete and add. It seems that directly modify the VName member of the TDocVariantData is the most efficient way, but it's a private member.

Any advice? Thanks in advance.

BTW: The mail server of mORMot official forum seems to have a problem, when I post a topic, it shows:

An error was encountered
Error: Could not connect to smtp host "217.70.184.11" (111) (Connection refused).

Solution

  • This question was solved in mORMot forum.