Einzelnen Beitrag anzeigen

Benutzerbild von DeddyH
DeddyH

Registriert seit: 17. Sep 2006
Ort: Barchfeld
27.534 Beiträge
 
Delphi 11 Alexandria
 
#2

AW: JSON in Delphi

  Alt 24. Apr 2020, 16:00
Da mir dieses ganze Marshalling in Delphi immer etwas suspekt ist, mache ich sowas von Hand.
Delphi-Quellcode:
uses ..., System.JSON;

type
  TLinks = class
  private
    FStart: string;
    Fxxx: string;
    Fzzz: string;
  public
    class function FromJSON(const Obj: TJSONObject): TLinks; overload; static;
    class function FromJSON(const ObjStr: string): TLinks; overload; static;
    property Start: string read FStart write FStart;
    property xxx: string read Fxxx write Fxxx;
    property zzz: string read Fzzz write Fzzz;
  end;

...

class function TLinks.FromJSON(const Obj: TJSONObject): TLinks;
var
  Value: TJSONValue;
  lObj: TJSONObject;
  Dummy: string;
begin
  Result := nil;
  if Assigned(Obj) then
    begin
      Value := Obj.Values['links'];
      if Assigned(Value) and (Value is TJSONObject) then
        begin
          lObj := TJSONObject(Value);
          Result := TLinks.Create;
          if lObj.TryGetValue<string>('start', Dummy) then
            Result.Start := Dummy;
          if lObj.TryGetValue<string>('xxx', Dummy) then
            Result.xxx := Dummy;
          if lObj.TryGetValue<string>('zzz', Dummy) then
            Result.zzz := Dummy;
        end;
    end;
end;

class function TLinks.FromJSON(const ObjStr: string): TLinks;
var
  Obj: TJSONObject;
begin
  Obj := TJSONObject.ParseJSONValue(ObjStr) as TJSONObject;
  try
    Result := TLinks.FromJSON(Obj);
  finally
    Obj.Free;
  end;
end;
Detlef
"Ich habe Angst vor dem Tag, an dem die Technologie unsere menschlichen Interaktionen übertrumpft. Die Welt wird eine Generation von Idioten bekommen." (Albert Einstein)
Dieser Tag ist längst gekommen
  Mit Zitat antworten Zitat