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 对象转换为字符串并返回结果。
标签:begin,end,JsonObject,delphi,Prop,Person,json,Context,ChatGPT From: https://www.cnblogs.com/onlyou13/p/17109108.html