如何在JSON的DataSnap编组场跳过序列化?(How to skip field serial

2019-06-23 12:33发布

有没有跳过的JSON编组场系列化德尔福XE2的DataSnap一种通用的方式?

TBizObjects = class
  DataObject: TDataObject; -- skip this field on serializaing descendants
end;

Model = class(TBizObject);

Answer 1:

解决的办法很简单,但很好地隐藏。 你应该设定JSONMarshalled类属性为False你不想序列化或反序列化的字段。

假设你已经宣布要当元帅的下面的类:

type
  TPerson = class
  private
    FName: string;
    FSurname: string;
    FHeight: Integer;
  public
    constructor Create;
    destructor Destroy; override;
  end;

在这个声明中,仅FNameFHeight将被序列化和反序列化时, FSurname将被省略:

type
  TPerson = class
  private
    FName: string;
    [JSONMarshalled(False)]
    FSurname: string;
    FHeight: Integer;
  public
    constructor Create;
    destructor Destroy; override;
  end;

在这里,你有一些代码一起玩:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  Vcl.StdCtrls, Data.DBXJSON, Data.DBXJSONReflect;

type
  TPerson = class
  private
    FName: string;
    // try to comment and uncomment the following line and see the result
    [JSONMarshalled(False)]
    FSurname: string;
    FHeight: Integer;
  end;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  Person: TPerson;
  JSONString: string;
  JSONMarshal: TJSONMarshal;
  JSONUnMarshal: TJSONUnMarshal;
begin
  JSONMarshal := TJSONMarshal.Create(TJSONConverter.Create);
  try
    Person := TPerson.Create;
    try
      Person.FName := 'Petra';
      Person.FSurname := 'Kvitova';
      Person.FHeight := 183;

      JSONString := JSONMarshal.Marshal(Person).ToString;
      Memo1.Text := JSONString;
    finally
      FreeAndNil(Person);
    end;
  finally
    JSONMarshal.Free;
  end;

  JSONUnMarshal := TJSONUnMarshal.Create;
  try
    Person := JSONUnMarshal.Unmarshal(TJSONObject.ParseJSONValue(JSONString)) as TPerson;
    try
      ShowMessage(
        'Name: ' + Person.FName + sLineBreak +
        'Surname: ' + Person.FSurname + sLineBreak +
        'Height: ' + IntToStr(Person.FHeight) + ' cm'
      );
    finally
      Person.Free;
    end;
  finally
    JSONUnMarshal.Free;
  end;
end;

end.


文章来源: How to skip field serialization at JSON marshalling in DataSnap?