如何使用mormot将通用TList序列化为JSON

时间:2018-02-28 09:13:14

标签: delphi mormot

我想使用mORMot框架将通用TList序列化为JSON。

我知道有一个TDynList有一个方便的方法SaveToJSON,但它不适合我。

这是我的简单演示:

program Project3;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, System.Generics.Collections, SynCommons, SynDB, SynDBODBC, mORMot, mORMotSQLite3;

const
  CONN_STR =
    'Driver=MySQL ODBC 5.3 UNICODE Driver;Database=test;Server=127.0.0.1;Port=3306;UID=root;Pwd=';

type
  TRows = TList<Variant>;

  TDbService = class
    constructor Create(const ConnStr: RawUTF8); overload;
    destructor Destroy; override;
  protected
    fConnStr: RawUTF8;
    fProps: TODBCConnectionProperties;
    function GetConnection: TODBCConnectionProperties;
    function Query(const Sql: RawUTF8; const Params: array of const): TRows;
  public
    function GetSpecificUserList(Offset, Limit: Integer): TRows;
  end;

{ TDbService }

constructor TDbService.Create(const ConnStr: RawUTF8);
begin
  fConnStr := ConnStr;
end;

destructor TDbService.Destroy;
begin
  inherited;
end;

function TDbService.GetConnection: TODBCConnectionProperties;
begin
  Result := TODBCConnectionProperties.Create('', fConnStr, '', '');
end;

function TDbService.Query(const Sql: RawUTF8; const Params: array of const): TRows;
var
  Props: TODBCConnectionProperties;
  Row: ISQLDBRows;
  V: Variant;
begin
  Props := GetConnection;
  Result := TRows.Create;
  try
    try
      Row := Props.Execute(Sql, Params);
      while Row.Step do
      begin
        Row.RowDocVariant(V);
        Result.Add(Row);
      end;
    except
      FreeAndNil(Result);
      raise
    end;
  finally
    Props.Free;
  end;
end;

function TDbService.GetSpecificUserList(Offset, Limit: Integer): TRows;
begin
  // It calls a stored procedure, the Result will be a TList<Variant> .
  // Each Variant has properties like name, age, etc. as it's an User representation but not from any existed table) .
  Result := Query('CALL GetSpecUserList_P(?, ?)', [Offset, Limit]);
end;


{ Main }

procedure Main;
var
  DbService: TDbService;
  Rows: TList<Variant>;
begin
  DbService := TDbService.Create(CONN_STR);
  try
    Rows := DbService.GetSpecificUserList(0, 100);
    // How to serialize `Rows` to a JSON string? I'm not using TDynList because it could only hold of records, but not Variant.
  finally
    DbService.Free;
  end;
end;

begin
  Main;
end.

如何将Rows转换为JSON字符串?我没有使用TDynList,因为它只能保存记录,但不能保存Variant。

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

最后,我写了一个像这样的工具函数:

function VariantListToJson(const List: TList<Variant>): RawUTF8;
var
  Item: Variant;
  S: RawUTF8;
begin
  Result := '[';
  for Item in List do
  begin
    S := VariantSaveJSON(Item);
    Result := Result + S + ',';
  end;
  if Result <> '[' then
    Delete(Result, Length(Result), 1);
  Result := Result + ']';
end;