Datasnap RESTful JSON Result About?

2019-06-07 09:58发布

问题:

I have a TDataset JSON helper function.

I want to result return the following:

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

But.Does not work.The return the following:

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

I want to remove extra [ character...

How to extract this data and return ?

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

My TDataset JSON Helper function :

 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;

How can I solve this problem ?

回答1:

GetInvocationMetadata().ResponseCode := 200;

GetInvocationMetadata().ResponseContent := '{"rid":"2","firstname":"veli","lastname":"deli"},{"rid":"1","firstname":"ismail","lastname":"kocacan"}';



回答2:

FYI, we added a more complete and faster function, in our Open Source repository.

It is part of our mORMot framework, but can be used as a stand-alone unit, not tied to other features.

See in SynVirtualDataSet.pas:

function DataSetToJSON(Data: TDataSet): RawUTF8 

See this commit and the associated forum thread.