Einzelnen Beitrag anzeigen

Benutzerbild von Uwe Raabe
Uwe Raabe

Registriert seit: 20. Jan 2006
Ort: Lübbecke
11.024 Beiträge
 
Delphi 12 Athens
 
#19

AW: JSON einlesen - Hilfe für Anfänger

  Alt 21. Dez 2021, 17:33
Also ich weiß nicht was man da sonst noch zu schreiben soll. Ich habe dir doch auch schon ein Beispiel gemacht.
Das compiliert aber so nicht. Wenn man sich damit dann nicht auskennt, wirft man es halt schnell gleich wieder weg.

Bis auf den Dateinamen für die JSON-Datei sollte es so gehen:
Delphi-Quellcode:
program TestJSON1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IOUtils,
  REST.Json.Types,
  REST.Json;

type
  TBlock = class
  private
    FListe1: TArray<string>;
    FListe4: TArray<Integer>;
    FInt_1: Integer;
    FTxt_1: string;
    FBool_1: Boolean;
    FReal_1: Real;
  public
    property Liste1: TArray<string> read FListe1;
    property Liste4: TArray<Integer> read FListe4;
    property Int_1: Integer read FInt_1;
    property Txt_1: string read FTxt_1;
    property Bool_1: Boolean read FBool_1;
    property Real_1: Real read FReal_1;
  end;

  TContainer = class
  private
    { ja, wir könnten hier auch FBlöcke schreiben, aber das sind so Dinge, die bringe ich einfach nicht übers Herz. }
    [JSONName('Blöcke')] // needs REST.Json.Types
    FBloecke: TArray<TBlock>;
  public
    destructor Destroy; override;
    property Bloecke: TArray<TBlock> read FBloecke;
  end;

destructor TContainer.Destroy;
var
  item: TBlock;
begin
  for item in FBloecke do
    item.Free;

  inherited;
end;

procedure ParseJson();
var
  block: TBlock;
  FileContent: String;
  Container: TContainer;
begin
  FileContent := TFile.ReadAllText('<path\to\file.json>');
  Container := TJson.JsonToObject<TContainer>(FileContent);
  try
    for block in Container.Bloecke do
      Writeln(block.Txt_1);
  finally
    Container.Free;
  end;
end;

begin
  try
    ParseJson;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.
Uwe Raabe
Certified Delphi Master Developer
Embarcadero MVP
Blog: The Art of Delphi Programming
  Mit Zitat antworten Zitat