unit Format.JSON;
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
System.JSON.Writers,
System.JSON.Readers,
System.JSON.Types;
type
TJsonStringWriter =
class(TJsonTextWriter)
private
FStringBuilder: TStringBuilder;
FStringWriter: TStringWriter;
public
constructor Create;
destructor Destroy;
override;
function ToString:
string;
override;
end;
TJsonStreamReader =
class(TJsonTextReader)
private
FStreamReader: TStreamReader;
public
constructor Create(
const AJsonObject: TJSONObject);
destructor Destroy;
override;
end;
function JsonObjectToFormattedString(
const AJsonObject: TJSONObject):
string;
implementation
function JsonObjectToFormattedString(
const AJsonObject: TJSONObject):
string;
var
JsonWriter: TJsonStringWriter;
JsonReader : TJsonStreamReader;
begin
JsonReader := TJsonStreamReader.Create(AJsonObject);
try
JsonWriter := TJsonStringWriter.Create;
try
JsonWriter.Formatting := TJsonFormatting.Indented;
JsonWriter.WriteToken(JsonReader);
Result := JsonWriter.ToString;
finally
JsonWriter.Free;
end;
finally
JsonReader.Free;
end;
end;
{ TJsonStringWriter }
constructor TJsonStringWriter.Create;
begin
FStringBuilder := TStringBuilder.Create;
FStringWriter := TStringWriter.Create(FStringBuilder);
inherited Create(FStringWriter);
end;
destructor TJsonStringWriter.Destroy;
begin
inherited Destroy;
FStringWriter.Free;
FStringBuilder.Free;
end;
function TJsonStringWriter.ToString:
string;
begin
Result := FStringBuilder.ToString;
end;
{ TJsonStreamReader }
constructor TJsonStreamReader.Create(
const AJsonObject: TJSONObject);
var
LBytes : TBytes;
LStream : TStream;
Len : Integer;
begin
Len := AJsonObject.ToString.Length * 6;
// <--- das ist dann natürlich Quatsch, vielleicht kann man die benötigte Länge auch anderes bestimmen.
SetLength(LBytes, Len);
Len := AJsonObject.ToBytes(LBytes, 0);
SetLength(LBytes, Len);
LStream := TMemoryStream.Create;
LStream.WriteBuffer(LBytes, Length(LBytes));
Assert(LStream.Size <> 0);
LStream.Position := 0;
FStreamReader := TStreamReader.Create(LStream);
inherited Create(FStreamReader);
end;
destructor TJsonStreamReader.Destroy;
begin
inherited;
FStreamReader.Free;
end;
end.