DELPHI 10.1 BERLIN新增TDBXJSONStream类,用于方便地将数据序列为JSON,和将JSON还原出来数据。
DATASNAP远程方法也相应地增加了支持返回TDBXJSONStream。必须引用 Data.DBXCommon单元。
url rest方式呼叫远程方法,直接返回JSON数据。
易博龙关于它有这么一段注释:
A TDBXJSONStream type may be used as a parameter or return value in server methods.
Use this type to pass a JSON stream between DataSnap servers and clients.
A TDBXJSONStream is either writable or readable, but not both.
IN parameters are used to pass a readable TDBXJSONStream to a server method.
OUT parameters and return values are used to pass a TDBXJSONStream that the server method has written.
下面的代码仅供语法演示,无任何实际意义。
服务端代码:
function TServerMethods1.QuerySql4(const accountNo, sql: string): TDBXJSONStream;
var
d: TfrmDB;
procedure WritePair(const sProperty, sFieldName, sFieldValue: string);
begin
Result.Writer.WritePropertyName(sProperty);
Result.Writer.WriteValue(sFieldValue);
end;
begin
Result := nil;
if (accountNo = '') or (sql = '') then
Exit;
d := GetDBPool(accountNo).Lock;
if not Assigned(d) then
Exit;
try
d.qryOpen.Close;
d.qryOpen.sql.Clear;
d.qryOpen.sql.Text := sql;
d.qryOpen.Open;
Result := TDBXJSONStream.Create;
Result.Writer.WriteStartArray;
try
while not d.qryOpen.Eof do
begin
try
Result.Writer.WriteStartObject;
// WritePair();
finally
Result.Writer.WriteEndObject;
d.qryOpen.Next;
end;
end;
finally
Result.Writer.WriteEndArray;
Result.Writer.Close;
end;
finally
d.qryOpen.Close;
GetDBPool(accountNo).Unlock(d);
end;
end;
客户端代码:
procedure TForm5.Button1Click(Sender: TObject);
var
aServer : TServerMethods1Client;
js : TDBXJSONStream;
begin
aServer := TServerMethods1Client.Create(Self.SQLConnection1.DBXConnection);
try
js := aServer.QueryHotel(Edit1.Text);
js.Reader.Rewind;
while (js.Reader.Read) do
begin
case js.Reader.TokenType of
TJsonToken.StartArray:
begin
while (js.Reader.Read) do
begin
case js.Reader.TokenType of
TJsonToken.PropertyName:
begin
ListView1.Items.Add.Text := js.Reader.Value.ToString + ': ' + js.Reader.ReadAsString;
end;
end;
end;
end;
end;
end;
finally
aServer.Free;
end;
end;