REST风格的DataSnap JSON结果一回事呢?(Datasnap RESTful JSON

2019-09-22 16:13发布

我有一个TDataSet的JSON助手的功能。

我想结果返回如下:

{"result":[{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}]}

But.Does不work.The返回以下内容:

{"result":[[{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}]]}

我想删除多余的[字符...

如何提取此数据并返回?

{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}

我TDataSet的JSON助手功能:

 TDatasetJSONHelper = class helper for TDataset
  public
    function ToJSONData: TJSONArray;
    function ToJSONDataWrapper: TJSONValue;
  end;

function TDatasetJSONHelper.ToJSONData: TJSONArray;
var
  jso: TJSONObject;
  jsa: TJSONArray;
  jsp: TJsonPair;
  J: Integer;
  avalue: TJSONValue;
begin
  Self.Close;
  Self.Open;
  jsa := TJSONArray.Create();
  while not Self.Eof do
  begin
    jso := TJSONObject.Create();
    for J := 0 to FieldCount - 1 do
      jso.AddPair(TJsonPair.Create(Fields[J].DisplayName, Fields[J].Value));
    jsa.AddElement(jso);
    Self.Next;
  end;
  Self.Close;
  Result := jsa;
end;


function TDatasetJSONHelper.ToJSONDataWrapper: TJSONValue;
var
  aJSON: TJSONObject;
  apair: TJsonPair;
  avalue: TJSONValue;
begin
  aJSON := TJSONObject.ParseJSONValue
    (TEncoding.ASCII.GetBytes
    ('{"result":[[{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}]]}'),
    0) as TJSONObject;

  apair := aJSON.Get(0);
  avalue := apair.JsonValue;

  // ??? avalue := '{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}';
  Result := avalue;
end;






function TServerMethods1.GetPersonList: TJSONArray;
begin
  Result := dm.AdoQuery1.ToJSONData;
end;

function TServerMethods1.GetPersonList2: TJSONValue;
begin
  Result := dm.AdoQuery1.ToJSONDataWrapper;
end;

我怎么解决这个问题 ?

Answer 1:

。GetInvocationMetadata()ResponseCode:= 200;

GetInvocationMetadata()ResponseContent:=“{ “RID”: “2”, “姓名”: “帆”, “姓”: “熟食店”},{ “RID”: “1”, “姓名”: “伊斯梅尔” , “姓氏”: “kocacan”}“;



Answer 2:

仅供参考,我们增加了一个更加完整和更快速的功能,在我们的开源库。

这是我们mORMot框架的一部分,但可以作为一个独立的单元,不依赖于其他功能。

见SynVirtualDataSet.pas :

function DataSetToJSON(Data: TDataSet): RawUTF8 

见这个承诺和相关的论坛主题 。



文章来源: Datasnap RESTful JSON Result About?