使用TMemoryStream的Delphi XE2 Datasnap TObject

时间:2012-04-19 09:41:12

标签: delphi delphi-xe2 datasnap

如何通过datasnap传输带有TMemoryStream的TObject?

TMyObject = class(TBizObject)
  FText: TMemoryStream;  <-- Content not sent
  ...
end

在服务器端

TServerMethods.GetMyClass(const AId: Integer): TMyObject
begin
  Result := TMyObject.find(AId);
end;

在客户端TMyObject正确解组,但FText内容为空。

TMemoryStream Json内容

"FText": {
        "type":"System.Classes.TMemoryStream",
        "id":2,
        "fields":{
            "FCapacity":16384,
            "FSize":11788,
            "FPosition":11788
        }
    }

1 个答案:

答案 0 :(得分:5)

关键是创建字段类型为 * 的TConverterEvent和TReverterEvent。没有源代码就很难找到解决方案。

procedure RegisterDatasnapConvertersAndReverters;
var
  LConverter: TConverterEvent;
  LReverter: TReverterEvent;
begin
  LConverter := TConverterEvent.Create(TMemoryStream, '*' {FIELD_ANY});
  LConverter.TypeStringConverter := function (Data: TObject): string
    var
      stream: TMemoryStream;
    begin
      stream := TMemoryStream(Data);
      stream.Position := 0;
      Result := EncodeBase64(stream.Memory, stream.Size);
    end;
  TJSONConverters.AddConverter(LConverter);

  LReverter := TReverterEvent.Create(TMemoryStream, '*' {FIELD_ANY});
  LReverter.TypeStringReverter := function(Data: string): TObject
    var
      bytes: TBytes;
    begin
      bytes := DecodeBase64(Data);
      Result := TMemoryStream.Create;
      if nil <> bytes then
        TMemoryStream(Result).WriteBuffer(bytes[0], Length(bytes));
    end;
  TJSONConverters.AddReverter(LReverter);
end;

initialization
  RegisterDatasnapConvertersAndReverters;