频道分类

Delphi10.3通过REST单元使类和JSON数据互相转换

作者:admin 来源: 日期:2019/10/1 16:44:27 人气: 标签:

 
Delphi10.3通过REST单元使类和JSON数据互相转换
一、我们定义一个简单的类

复制代码
  TPeople = class
  private
    FName: string;
    FScore: Integer;
    FAge: TDateTime;
  public
    property Name: string read FName write FName;
    property Score: Integer read FScore write FScore;
    property Age: TDateTime read FAge write FAge;
  end;
复制代码
 

二、我们写下如下Delphi代码:

复制代码
uses
  REST.Json,
  System.Json,
  System.Types,
  System.Json.Types,
  System.Json.Writers,
  System.Json.Builders;

procedure TForm1.Button5Click(Sender: TObject);
var
  I: Integer;
  m_Str: string;
  m_People: TPeople;
begin
  Memo1.Clear;
  Memo2.Clear;
  //实例化类
  m_People := TPeople.Create;
  try
    m_People.Name := '张三';
    m_People.Age := Now;
    m_People.Score := 98;
    //类转JSON
    m_Str := TJson.ObjectToJsonString(m_People);
  finally
    m_People.Free;
  end;
  //输出JSON
  Memo1.Lines.Add(m_Str);

  //JSON转类
  m_People := TJson.JsonToObject<TPeople>(m_Str);
  try
    //输出类
    Memo2.Lines.Add(Format('姓名:%s,分数:%d,年龄:%s', [m_People.Name, m_People.Score, FormatDateTime('yyyy-mm-dd', m_People.Age)]));
  finally
    m_People.Free;
  end;
end;


来源:https://www.cnblogs.com/tianpan2019/p/10498785.html