jsondelphiserializationdelphi-xe6

Does anyone have an example of round trip serialization of JSON in Delphi XE6?


I want to code a (what I would think is a simple) round trip serialization of an object in Delphi. But, I can't seem to figure out how to do it to/from JSON. I can, and have for some time, do it with XML.

However, the example and explanation I've found in the standard Embarcadero docs, e.g. local help, DocWiki, etc. haven't helped me much.

Preferably, I am looking for an actual working example using XE(6) native libraries or components -- but, I would be grateful for links to any writeups (docs, articles, posts, etc..) and/or any other libraries that anyone has used to get this working.


Solution

  • I would avoid using the native framework, the main reason being that it serializes private members of objects, which I think breaks OOP encapsulation principles. It would be more correct imho to serialize the published properties of classes. It breaks interoperability with other languages.

    Anyway, here is a basic example.

    implementation
    
    uses
      Serializable,
      REST.JsonReflect,
      System.Json,
      System.SysUtils;
    
    
    { TMain }
    
    procedure TMain.Run;
    var
      mySerializable: TMySerializable;
      marshaller: TJSONMarshal;
      unMarshaller: TJSONUnMarshal;
      jsonValue: TJSONValue;
    begin
      mySerializable := TMySerializable.Create;
      mySerializable.MyInt := 42;
      mySerializable.MyString := 'The Answer';
      // Serialize
      marshaller := TJSONMarshal.Create;
      jsonValue := marshaller.Marshal(mySerializable);
      marshaller.Free;
      mySerializable.Free;
      mySerializable := nil;
      WriteLn('JSon value:');
      WriteLn(jsonValue.ToString);
      // Deserialize
      unMarshaller := TJSONUnMarshal.Create;
      mySerializable := TMySerializable(unMarshaller.CreateObject(TMySerializable, TJSONObject(jsonValue)));
      WriteLn('mySerializable.MyInt: ' + IntToStr(mySerializable.MyInt));
      WriteLn('mySerializable.MyString: ' + mySerializable.MyString);
    
      jsonValue.Free;
      mySerializable.Free;
      unMarshaller.Free;
      ReadLn;
    
    end;
    

    And the unit Serializable defines a simple test class.

    unit Serializable;
    
    interface
    
    uses
      System.Classes;
    
    type
      TMySerializable = class(TPersistent)
      private
        FMyString: string;
        FMyInt: Integer;
      published
        property MyInt: Integer read FMyInt write FMyInt;
        property MyString: string read FMyString write FMyString;
      end;
    
    implementation
    
    end.