2012-04-19 129 views
2

如何通過datasnap與TMemoryStream傳輸TObject?德爾福XE2 Datasnap TObject與TMemoryStream

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

上,除了用FText內容服務器端

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

在客戶端TMyObject正確地解組是空的。

內存流的Json內容

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

查看'MarshalUnmarshal'示例項目。 – 2012-04-19 11:03:59

+0

我已經看過,知道如何註冊轉換器的對象字段。問題是,我有很多對象,我需要(實際上需要)全局註冊TMemoryStream轉換器。或者我錯過了什麼? – Raido 2012-04-19 12:58:20

回答

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;