onlyou13

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
uses
  System.Rtti, System.JSON;

type
  TPerson = class
  public
    Name: string;
    Age: Integer;
  end;

function ObjectToJSON(AObject: TObject): string;
var
  Context: TRttiContext;
  RttiType: TRttiType;
  Prop: TRttiProperty;
  Value: TValue;
  JsonObject: TJSONObject;
begin
  Context := TRttiContext.Create;
  try
    RttiType := Context.GetType(AObject.ClassType);
    JsonObject := TJSONObject.Create;
    try
      for Prop in RttiType.GetProperties do
      begin
        if Prop.IsReadable then
        begin
          Value := Prop.GetValue(AObject);
          JsonObject.AddPair(Prop.Name, Value.AsString);
        end;
      end;
      Result := JsonObject.ToString;
    finally
      JsonObject.Free;
    end;
  finally
    Context.Free;
  end;
end;

var
  Person: TPerson;
begin
  Person := TPerson.Create;
  try
    Person.Name := 'John Doe';
    Person.Age := 30;
    WriteLn(ObjectToJSON(Person));
  finally
    Person.Free;
  end;
end.

这段代码使用了 RTTI 来获取类的公共属性,并将其值添加到一个 JSON 对象中。最后,将 JSON 对象转换为字符串并返回结果。

 
posted on 2023-02-10 15:26  onlyou13  阅读(107)  评论(0编辑  收藏  举报