Better mention this : I'm using Delphi XE2 - but XE or 2010 should do the trick too :-)
This Question is now in Quality Central QC#99313 please vote it up :-)
As of 10-20-2011 Embarcadero has marked the QC report as RESOLVED. Solution was provided by SilverKnight. But the lack of information from Embarcadero worries me. Since the solution suggests using other source code than the one explained in XE(2) Help system, other forums and CC. But have a look at the QC yourself.
Given these type declarations:
type
TTestObject : Class
aList : TStringList;
function Marshal : TJSonObject;
end;
TTestObjectList<T:TestObject> : Class(TObjectList<T>)
function Marshal : TJSonObject; // How to write this ?
end;
I would like to implement a Marshal method for TTestObjectList. To my best knowledge - I should register a converter for TTestObject and for the beauty of it - call Marshal for each element.
The Marshal for TTestObject registers this converter:
RegisterConverter(TStringList,
function(Data: TObject): TListOfStrings
var
i, Count: Integer;
begin
Count := TStringList(Data).Count;
SetLength(Result, Count);
for i := 0 to Count - 1 do
Result[i] := TStringList(Data)[i];
end);
The Generic TTestObjectList Marshal method:
function TTestObjectList<T>.Marshal: TJSONObject;
var
Mar : TJsonMarshal; // is actually a property on the list.
begin
Mar := TJsonMarshal.Create(TJSONConverter.Create);
try
RegisterConverter(TTestObject,
function(Data: TObject): TObject
begin
Result := TTestObject(Data).Marshal;
end);
Result := Mar.Marshal(Self) as TJSONObject;
finally
Mar.Free;
end;
end;
Here is a simplified example of using the list.
var
aTestobj : TTestObject;
aList : TTestObjectList<TTestObject>;
aJsonObject : TJsonObject;
begin
aTestObj := TTestObject.Create; // constructor creates and fills TStringlist with dummy data.
aJsonObject := aTestObj.Marshal; // This works as intended.
aList := TTestObjectList<TTestObject>.Create;
aJsonObject := aList.Marshal; // Fails with tkpointer is unknown ....
end;
Of course I have similar functionality for restoring (unmarshal). But the above code should work - at least to my best knowledge.
So if anyone can point out to me :
Why the List fails to marshal?
I know I have the TJsonMarshal property on my list - but it also has a converter/reverter.
Changing to a TTypeStringConverter (instead of TTypeObjectConverter) will return a valid string. But I like the idea of working on a TJsonObject all along. Otherwise I would have the same problem (or something similar) when doing the unmarshalling from a string to TTestObject.
Any advice / ideas are most welcome.