delphi 序列化JSON升级方法

发布时间 2023-08-14 15:00:41作者: jjw
  TConverterCommon = class(TJsonConverter)
  public
    function CanConvert(ATypeInf: PTypeInfo): Boolean; override;
    function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue;
      const ASerializer: TJsonSerializer): TValue; override;
    procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue;
      const ASerializer: TJsonSerializer); override;
  end;



{ TConverterCommon }

function TConverterCommon.CanConvert(ATypeInf: PTypeInfo): Boolean;
begin
  Result := True;
end;

function TConverterCommon.ReadJson(const AReader: TJsonReader;
  ATypeInf: PTypeInfo; const AExistingValue: TValue;
  const ASerializer: TJsonSerializer): TValue;
begin
  raise Exception.Create('未实现');
end;

procedure TConverterCommon.WriteJson(const AWriter: TJsonWriter;
  const AValue: TValue; const ASerializer: TJsonSerializer);
begin
  if AValue.IsObjectInstance then
  begin
    var LType := TRttiContext.Create.GetType(AValue.TypeInfo);
    for var LProp in LType.GetProperties do
    begin
      if LProp.Name = 'List' then
      begin
        var Value := LProp.GetValue(AValue.AsObject);

        if not Value.IsArray then raise Exception.Create('???');
        
        AWriter.WriteStartArray;
        for var I := 0 to Value.GetArrayLength - 1 do
          ASerializer.Serialize(AWriter, Value.GetArrayElement(I));
        AWriter.WriteEndArray;

        Exit;
      end;
    end;
  end;
end;
  TObjectValue = class
  private
    FValue: string;
  public
    constructor Create(AValue: string);
    property Value: string read FValue write FValue;
  end;
  
  TTestObject = class
  private
    FObjectList: TObjectList<TObjectValue>;
  public
    constructor Create;
    destructor Destroy; override;
    [JsonConverterAttribute(TConverterCommon)]   //在这打标签就行了
    property ObjectList: TObjectList<TObjectValue> read FObjectList;
  end;