如何使用mormot将通用TList序列化为JSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用mormot将通用TList序列化为JSON相关的知识,希望对你有一定的参考价值。
我想使用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。
非常感谢任何帮助,谢谢。
答案
最后,我写了一个这样的工具函数:
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;
以上是关于如何使用mormot将通用TList序列化为JSON的主要内容,如果未能解决你的问题,请参考以下文章
System.Text.Json:当json配置具有通用JsonStringEnumConverter时,如何将单个枚举序列化为数字[重复]
使用 Jackson 将通用 java 对象序列化为 JSON