Wednesday, September 2, 2009

Custom Marshalling/UnMarshalling in Delphi 2010

Introduction
Some days ago, Embarcadero has presented the new version of RAD Studio, 2010.
The are many new features, but you can find in a lot places around the web, so
I won’t repeat them here.


One of the things widely requested from all Delphi programmers all over the world over the past few years, including myself, is
certainly a new and more powerful RTTI.


The new system of RTTI has finally arrived, and pave the way for a large number of applications.
One area that has benefited from the new RTTI is for sure the marshaled objects.


Marshaling is defined as follows:


“In computer science, marshalling (similar to serialization) is the process of
transforming the memory representation of an object to a data format suitable for
storage or transmission. It is typically used when data must be moved between
different parts of a computer program or from one program to another.
The opposite, or reverse, of marshalling is called unmarshalling (demarshalling) (similar to deserialization).”
–WikiPedia


In Delphi 2010 the process of serialization and deserialization is handled respectively by a Marshaller and an Unmarshaller.


The built-in format for the serialization of any Delphi object is JSON.
There are 2 main classes responsible for serializing objects into JSON, both present in the unit DBXJSONReflect:
- TJSONMarshal
- TJSONUnMarshal


Let’s say you have an object defined as follow:



Code



To serialize and deserialize an instance of TKid it requires the following steps:



Code

  1. var
  2. Mar: TJSONMarshal; //Serializer
  3. UnMar: TJSONUnMarshal; //UnSerializer
  4. Kid: TKid; //The Object to serialize
  5. SerializedKid: TJSONObject; //Serialized for of object
  6. begin
  7. Mar := TJSONMarshal.Create(TJSONConverter.Create);
  8. try
  9. Kid := TKid.Create;
  10. try
  11. Kid.FirstName := 'Daniele';
  12. Kid.LastName := 'Teti';
  13. Kid.Age := 29;
  14. SerializedKid := Mar.Marshal(Kid) as TJSONObject;
  15. finally
  16. FreeAndNil(Kid);
  17. end;
  18. finally
  19. Mar.Free;
  20. end;
  21. //Output the JSON version of the Kid object
  22. WriteLn(SerializedKid.ToString);
  23. // UnMarshalling Kid
  24. UnMar := TJSONUnMarshal.Create;
  25. try
  26. Kid := UnMar.UnMarshal(SerializedKid) as TKid;
  27. try
  28. //now kid is the same as before marshalling
  29. Assert(Kid.FirstName = 'Daniele');
  30. Assert(Kid.LastName = 'Teti');
  31. Assert(Kid.Age = 29);
  32. finally
  33. Kid.Free;
  34. end;
  35. finally
  36. UnMar.Free;
  37. end;
  38. end;


Simple, isn’t it?
To access the JSON string that is our object, we must call the method ToString.
The JSON representation of this object SerializedKid can be saved to file,
sent to a remote server, used by a Web page from a web service, stored on a database or sent into space (!!!).
The Delphi application re-read the JSON string, you can recreate the object as it was at the time of serialization.
But anyone with a JSON parser can still read the data in our object, even non Delphi client.
These are the advantages of having used an open format and standard.


So far the simple part …
How serialize a field differently from the default?


Suppose we add the date of birth to our TKid:



Code

  1. type
  2. TKid = class
  3. FirstName: String;
  4. LastName: String;
  5. Age: Integer;
  6. BornDate: TDateTime;
  7. end;


Serialize a TDateTime, localized and that I have in JSON string is a float, because for Delphi TDateTime is a decimal number.
If I read the data from another program Delphi, no problem, but if I wanted to read a script in JavaScript? or. NET? or Ruby?
Then I use a format “DATA” to understand, even for these languages.
The new engine provides the serialization too.
Is needed, however, to tell the Marshaller and UnMarsheller how to represent and reconstruct a particular
object field by two statements like the following:



Code



The anonymous method is called when the marshaller serializes the field ‘BornDate’ is called “Converter” while Unmarshaller anonymous method that calls when he has to reconstruct the object from the JSON string is the “Reverter”.
Thus serializing a TKid assure you that my object is readable both by Delphi from another language without loss of information.


But what happens when I have to serialize a complex type?


Suppose we extend TKid this:




Code

  1. type
  2. TTeenager = class(TKid)
  3. Phones: TStringList;
  4. constructor Create; virtual;
  5. destructor Destroy; virtual;
  6. end;


We must define a Converter and a Reverter for the TStringList class.
We can do it this way:



Code



There are different types of Converter and Reverter.
In the the DBXJSONReflect there are 8 types of converters:


Code




Each of them deals with a particular conversion object representation in the final serialization, in our case we will use them to convert to JSON.


Also in the DBXJSONReflect unit are defined many “Reverter” dealing with retrieving
the serialized version of the data and use it to reconstruct the object previously serialized.
Because they are complementary to the Converter, I will not copy them here.


As a final example, we derive from TProgrammer by TTeenager adding a list of Laptops in the properties.


Is therefore necessary to introduce a new pair of Converter / Reverter.
In this example I have defined all the converter and reverter in another unit in
order to have more readable code:




  1. type
  2. TLaptop = class
  3. Model: String;
  4. Price: Currency;
  5. constructor Create(AModel: String; APrice: Currency);
  6. end;
  7. TLaptops = TObjectList;
  8. TProgrammer = class(TTeenager)
  9. Laptops: TLaptops;
  10. constructor Create; override;
  11. destructor Destroy; override;
  12. class function CreateAndInitialize: TProgrammer;
  13. end;
  14. // Implementation code…
  15. var
  16. Marshaller: TJSONMarshal;
  17. UnMarshaller: TJSONUnMarshal;
  18. Programmer: TProgrammer;
  19. Value, JSONProgrammer: TJSONObject;
  20. begin
  21. Marshaller := TJSONMarshal.Create(TJSONConverter.Create);
  22. try
  23. Marshaller.RegisterConverter(TProgrammer, 'BornDate', ISODateTimeConverter);
  24. Marshaller.RegisterConverter(TStringList, StringListConverter);
  25. Marshaller.RegisterConverter(TProgrammer, 'Laptops', LaptopListConverter);
  26. Programmer := TProgrammer.CreateAndInitialize;
  27. try
  28. Value := Marshaller.Marshal(Programmer) as TJSONObject;
  29. finally
  30. Programmer.Free;
  31. end;
  32. // UnMarshalling Programmer
  33. UnMarshaller := TJSONUnMarshal.Create;
  34. try
  35. UnMarshaller.RegisterReverter(TProgrammer, 'BornDate', ISODateTimeReverter);
  36. UnMarshaller.RegisterReverter(TStringList, StringListReverter);
  37. UnMarshaller.RegisterReverter(TProgrammer, 'Laptops', LaptopListReverter);
  38. Programmer := UnMarshaller.Unmarshal(Value) as TProgrammer;
  39. try
  40. Assert('Daniele' = Programmer.FirstName);
  41. Assert('Teti' = Programmer.LastName);
  42. Assert(29 = Programmer.Age);
  43. Assert(EncodeDate(1979, 11, 4) = Programmer.BornDate);
  44. Assert(3 = Programmer.Phones.Count);
  45. Assert('NUMBER01′ = Programmer.Phones[0]);
  46. Assert('NUMBER02′ = Programmer.Phones[1]);
  47. Assert('NUMBER03′ = Programmer.Phones[2]);
  48. Assert('HP Presario C700′ = Programmer.Laptops[0].Model);
  49. Assert(1000 = Programmer.Laptops[0].Price);
  50. Assert('Toshiba Satellite Pro' = Programmer.Laptops[1].Model);
  51. Assert(800 = Programmer.Laptops[1].Price);
  52. Assert('IBM Travelmate 500′ = Programmer.Laptops[2].Model);
  53. Assert(1300 = Programmer.Laptops[2].Price);
  54. finally
  55. Programmer.Free;
  56. end;
  57. finally
  58. UnMarshaller.Free;
  59. end;
  60. finally
  61. Marshaller.Free;
  62. end;
  63. end;


Unit CustomConverter.pas contains all needed Converters/Reverts as anon methods.




  1. unit CustomConverter;
  2. interface
  3. uses
  4. DBXJSONReflect,
  5. MyObjects; //Needed by converter and reverter for TLaptops
  6. var
  7. ISODateTimeConverter: TStringConverter;
  8. ISODateTimeReverter: TStringReverter;
  9. StringListConverter: TTypeStringsConverter;
  10. StringListReverter: TTypeStringsReverter;
  11. LaptopListConverter: TObjectsConverter;
  12. LaptopListReverter: TObjectsReverter;
  13. implementation
  14. uses
  15. SysUtils, RTTI, DateUtils, Classes;
  16. initialization
  17. LaptopListConverter := function(Data: TObject; Field: String): TListOfObjects
  18. var
  19. Laptops: TLaptops;
  20. i: integer;
  21. begin
  22. Laptops := TProgrammer(Data).Laptops;
  23. SetLength(Result, Laptops.Count);
  24. if Laptops.Count > 0 then
  25. for I := 0 to Laptops.Count - 1 do
  26. Result[I] := Laptops[i];
  27. end;
  28. LaptopListReverter := procedure(Data: TObject; Field: String; Args: TListOfObjects)
  29. var
  30. obj: TObject;
  31. Laptops: TLaptops;
  32. Laptop: TLaptop;
  33. i: integer;
  34. begin
  35. Laptops := TProgrammer(Data).Laptops;
  36. Laptops.Clear;
  37. for obj in Args do
  38. begin
  39. laptop := obj as TLaptop;
  40. Laptops.Add(TLaptop.Create(laptop.Model, laptop.Price));
  41. end;
  42. end;
  43. StringListConverter := function(Data: TObject): TListOfStrings
  44. var
  45. i, count: integer;
  46. begin
  47. count := TStringList(Data).count;
  48. SetLength(Result, count);
  49. for i := 0 to count - 1 do
  50. Result[i] := TStringList(Data)[i];
  51. end;
  52. StringListReverter := function(Data: TListOfStrings): TObject
  53. var
  54. StrList: TStringList;
  55. Str: string;
  56. begin
  57. StrList := TStringList.Create;
  58. for Str in Data do
  59. StrList.Add(Str);
  60. Result := StrList;
  61. end;
  62. ISODateTimeConverter := function(Data: TObject; Field: string): string
  63. var
  64. ctx: TRttiContext; date : TDateTime;
  65. begin
  66. date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType;
  67. Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', date);
  68. end;
  69. ISODateTimeReverter := procedure(Data: TObject; Field: string; Arg: string)
  70. var
  71. ctx: TRttiContext;
  72. datetime :
  73. TDateTime;
  74. begin
  75. datetime := EncodeDateTime(StrToInt(Copy(Arg, 1, 4)), StrToInt(Copy(Arg, 6, 2)), StrToInt(Copy(Arg, 9, 2)), StrToInt
  76. (Copy(Arg, 12, 2)), StrToInt(Copy(Arg, 15, 2)), StrToInt(Copy(Arg, 18, 2)), 0);
  77. ctx.GetType(Data.ClassType).GetField(Field).SetValue(Data, datetime);
  78. end;
  79. end.


Last hint…
Every serialization/unserialization process can create “warnings”.
Those warnings are collected into the “Warnings” property of the Ser/UnSer Object.


Conclusions
In this post I tried to introduce the basics of the new serialization engine in Delphi 2010.
During the next ITDevCon to be held in Italy next November 11.12, I’ll have a talk in which I will extensively talk about serialization and RTTI.
All interested smart developers are invited


ITALIAN P.S.
Se qualche programmatore italiano volesse avere la versione in italiano di questo post può lasciare un commento e vedrò di accontentarlo


You can find the DUnit project Source Code

No comments: