Einzelnen Beitrag anzeigen

Der schöne Günther

Registriert seit: 6. Mär 2013
6.110 Beiträge
 
Delphi 10 Seattle Enterprise
 
#5

AW: Erste Schritte mit Rest.Json.pas: Wann braucht man einen eigenen TJsonInterceptor

  Alt 2. Okt 2014, 12:18
Sagen wir mal so: Wenn ich nur mit Gewalt das "as TObject" reindrücke scheint alles zu funktionieren. Zumindest glaube ich das. Denn das grundlegende Verständnis fehlt mir weiterhin. Warum war das jetzt überhaupt nötig?

Interface-Interceptor über Attribut angehangen:
Delphi-Quellcode:
   TOuterType = class
      protected var
         [JSonName('someInt')]
         someInt: Integer;

         [JSonName('someIntf')] [JSONReflect(ctObject, rtObject, Unit2.TJSONInterfaceInterceptor)]
         someIntf: IInterface;

      public
         constructor Create();
   end;
Interceptor sieht so aus:

Delphi-Quellcode:
unit Unit2;

interface uses Rest.JSonReflect;

type
   TJSONInterfaceInterceptor = class(Rest.JsonReflect.TJSONInterceptor)
      protected
         function getAsIInterface(const Data: TObject; const Field: string): IInterface;
      public
         function ObjectConverter(Data: TObject; Field: string): TObject; override;
   end experimental;

implementation uses System.Rtti, Rest.Json;

{ TJSONInterfaceInterceptor }

function TJSONInterfaceInterceptor.getAsIInterface(const Data: TObject; const Field: string): IInterface;
var
   rttiType: TRttiType;
   rttiField: TRttiField;
   rttiContext: TRttiContext;
begin
   rttiType := rttiContext.GetType(Data.ClassType);
   rttiField := rttiType.GetField(Field);
   Result := rttiField.GetValue(Data).AsInterface;
end;

function TJSONInterfaceInterceptor.ObjectConverter(Data: TObject; Field: string): TObject;
begin
   Result := getAsIInterface(Data, Field) as TObject;
end;

initialization
   TJSONInterfaceInterceptor.ClassName();
end.

Erhaltene Ausgabe:
Code:
{"someSimpleField":42,"someAdvancedField":{"someValue":42.25}}
  Mit Zitat antworten Zitat