十、Delphi 把Json转成Delphi实体类

01、

十、Delphi 把Json转成Delphi实体类

 

unit TestClass;

interface

uses Generics.Collections, Rest.Json;

type
  TDataClass = class
  private
    FAA: String;
    FBB: String;
    FCC: Extended;
  public
    property AA: String read FAA write FAA;
    property BB: String read FBB write FBB;
    property CC: Extended read FCC write FCC;
    { function ToJsonString: string;
      class function FromJsonString(AJsonString: string): TDataClass; }
  end;

  TRootClass = class
  private
    FCode: Extended;
    FData: TArray<TDataClass>;
    FMsg: String;
    FMsgData: String;
    FPage: Extended;
    FTotal: Extended;
  public
    property code: Extended read FCode write FCode;
    property data: TArray<TDataClass> read FData write FData;
    property msg: String read FMsg write FMsg;
    property msgData: String read FMsgData write FMsgData;
    property page: Extended read FPage write FPage;
    property total: Extended read FTotal write FTotal;
    { destructor Destroy; override;
      function ToJsonString: string;
      class function FromJsonString(AJsonString: string): TRootClass; }
  end;

implementation

{ TDataClass }
{
  function TDataClass.ToJsonString: string;
  begin
  result := TJson.ObjectToJsonString(self);
  end;

  class function TDataClass.FromJsonString(AJsonString: string): TDataClass;
  begin
  result := TJson.JsonToObject<TDataClass>(AJsonString)
  end; }

{ TRootClass }
{
  destructor TRootClass.Destroy;
  var
  LdataItem: TDataClass;
  begin

  for LdataItem in FData do
  LdataItem.free;

  inherited;
  end;

  function TRootClass.ToJsonString: string;
  begin
  result := TJson.ObjectToJsonString(self);
  end;

  class function TRootClass.FromJsonString(AJsonString: string): TRootClass;
  begin
  result := TJson.JsonToObject<TRootClass>(AJsonString)
  end; }

end.

 

02、JSON文本如下:

{
    "code": 200,
    "page": 1,
    "total": 1502,
    "msg": "ERRMSG.COMMON.SUCCESS_CODE",
    "data": [
        {
            "AA": "2021-10-27 00:00:00",
            "BB": "CAD2007-A320-04R2",
            "CC": 8
        },
        {
            "AA": "DPG",
            "BB": "2021-10-08 10:01:55",
            "CC": 7
        }
    ],
    "msgData": ""
}

 

03、Delphi需要引用这些单元

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.StdCtrls,
  REST.Json,
  System.Json,
  System.Types,
  System.Json.Types,
  System.Json.Writers,
  System.Json.Builders,
  TestClass,
  Generics.Collections,
  System.Json.Serializers;

 

4、调用方法如下:

procedure TForm1.Button4Click(Sender: TObject);
var
  m_RootClass: TRootClass;
begin
  m_RootClass := TJson.JSONToObject<TRootClass>(Trim(Memo1.Text));
  Memo2.Lines.Add(m_RootClass.msg);
end;

十、Delphi 把Json转成Delphi实体类

 

 

不忘初心,如果您认为这篇文章有价值,认同作者的付出,可以微信二维码打赏任意金额给作者(微信号:382477247)哦,谢谢。

十、Delphi 把Json转成Delphi实体类

 

上一篇:table合并单元格函数


下一篇:Cesium.Property.getValueOrUndefined源码