delphi json和protobuf序列

delphi json和protobuf序列

unit serialize;
/// <author>cxg 2022-8-21</author>
interface

uses
  System.SysUtils, Grijjy.ProtocolBuffers,
  System.JSON.Serializers;

type
  TSerial = class
  public
    //unmarshal
    class function unmarshal<T: record>(const value: string): T; overload; //json
    class function unmarshal<T: record>(const value: tbytes): T; overload; //protobuf
    //marshal
    class function marshal<T: record>(const aRecord: T): string;   //json
    class function marshal2<T: record>(const aRecord: T): TBytes;  //protobuf
  end;

implementation

class function TSerial.marshal2<T>(const aRecord: T): TBytes;
begin
  var s: TgoProtocolBuffer := TgoProtocolBuffer.Create;
  Result := s.Serialize<T>(aRecord);
  s.Free;
end;

class function TSerial.marshal<T>(const aRecord: T): string;
begin
  var s: TJsonSerializer := TJsonSerializer.Create;
  Result := s.Serialize<T>(aRecord);
  s.Free;
end;

class function TSerial.unmarshal<T>(const value: string): T;
begin
  var s: TJsonSerializer := TJsonSerializer.Create;
  Result := s.Deserialize<T>(value);
  s.free;
end;

class function TSerial.unmarshal<T>(const value: tbytes): T;
begin
  var s: TgoProtocolBuffer := TgoProtocolBuffer.Create;
  s.Deserialize<T>(result, value);
  s.Free;
end;


end.

 

posted @ 2022-08-21 09:33  delphi中间件  阅读(172)  评论(0编辑  收藏  举报