delphi – 如何跳过DataSnap中JSON编组的字段序列化?

前端之家收集整理的这篇文章主要介绍了delphi – 如何跳过DataSnap中JSON编组的字段序列化?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Delphi XE2 DataSnap中,是否有通用的方法来跳过 JSON编组中的字段序列化?
TBizObjects = class
  DataObject: TDataObject; -- skip this field on serializaing descendants
end;

Model = class(TBizObject);

解决方法

解决方案非常简单但非常隐蔽.对于不希望序列化或反序列化的字段,应将 JSONMarshalled属性设置为False.

假设您已声明要编组的以下类:

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

在此声明中,只有FName和FHeight将被序列化和反序列化,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.
原文链接:https://www.f2er.com/delphi/239249.html

猜你在找的Delphi相关文章