How to de-serialize sub-property in delphi?
delphi, serialization
Solution
To serialize TSomething, it must be a sub-component. To do that you have to change one thing: don't derivate the two classes from TObject but rather from TComponent. Then in the TSomething constructor you call
Self.SetSubComponent(True);
FInally, as your class is a TComponent you won't need anymore the stuffs grabed from delphi.about because a TComponent can be directly serialized in a TStream by using WriteComponent / ReadComponent
You'll see that the process is easyer when choosing the right descendant. Here the choice is logic: if you want to serialize then use TComponent.
Problem
Since two days ago I started making my own simple classes from scratch, descended from `TObject`, nothing fancy. I also needed to write/read them to/from files, so after some searching, because I haven't yet learned all the ins and outs of serialization and don't fully get them, I borrowed serialization methods from here. It worked fine as I was testing it. Then I added another class as a property (that's what I'm referring to when I say sup-property: properties of a class that's a property in my class... that's confusing, it needs a proper name), following the advice in this SO question on how to actually do that. Now writing to file doesn't seem to raise any errors, then again I'm not sure the sub-properties are written properly or it's just garbage. Reading it back however does cause the Exception class EPropertyConvertError with message 'Invalid property type: TSomething' Since I'm just learning this, I'm not sure what is wrong. I do have a few wild guesses, one of which would be that the `TSomething = Class` maybe has to have it's own serialization methods? In that case how would that even work (cause even I don't believe this assumption)? Another would be that the code I borrowed from delphi.about.com can't handle these type of properties? And if so, how could I improve it? And if none of my guesses are correct, how would one make this work? (And I'm using DelphiXE2.) Code as per request: ``` TSomething = Class protected fNumber: integer; fLine: string; public procedure Assign(Source: TObject); published property Number: integer read fNumber write fNumber; property Line: string read fLine write fLine; End; TOther = Class public procedure LoadFromStream(const Stream: TMemoryStream); procedure SaveToStream(const Stream: TMemoryStream); constructor Create; virtual; destructor Destroy; override; protected fSomething: TSomething; procedure SetfSmth(AValue: TSomething); published property Something: TSomething read fSomething write SetfSomething; end; ``` The implementation for the methods has been borrowed from the two links that have been provided above, I see no need to retype that, unless asked for.