TConverterEx<T: class> = 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; { TConverterEx<T> } function TConverterEx<T>.CanConvert(ATypeInf: PTypeInfo): Boolean; begin Result := ATypeInf = TypeInfo(TObjectList<T>); end; function TConverterEx<T>.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue; const ASerializer: TJsonSerializer): TValue; begin raise Exception.Create('未实现'); end; procedure TConverterEx<T>.WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); begin if AValue.IsObjectInstance then begin var L := AValue.AsObject as TObjectList<T>; AWriter.WriteStartArray; for var I := 0 to L.Count - 1 do ASerializer.Serialize<T>(AWriter, L[I]); AWriter.WriteEndArray; end; end; procedure TForm1.FormCreate(Sender: TObject); begin var s := TJsonSerializer.Create; s.Formatting := TJsonFormatting.Indented; s.ContractResolver := TJsonDefaultContractResolver.Create(TJsonMemberSerialization.Public); s.Converters.Add(TConverterEx<TObjectValue>.Create); //一次注册,不用到处贴签了 var obj := TTestObject.Create; var jsonString := s.Serialize<TTestObject>(obj); Memo1.Lines.Add(jsonString); s.Free; end;
标签:AWriter,const,delphi,TValue,TConverterEx,Create,end,序列化,JOSN From: https://www.cnblogs.com/Jiaojiawang/p/17629447.html