unit Format.JSON;
interface
uses
System.SysUtils,
System.Classes,
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;
TJsonStringReader =
class(TJsonTextReader)
private
FStringReader: TStringReader;
public
constructor Create(
const AJson:
string);
destructor Destroy;
override;
end;
function FormatJsonString(
const AJson:
string):
string;
implementation
function FormatJsonString(
const AJson:
string):
string;
var
JsonWriter: TJsonStringWriter;
JsonReader: TJsonStringReader;
begin
JsonReader := TJsonStringReader.Create(AJson);
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
FStringWriter.Free;
FStringBuilder.Free;
inherited Destroy;
end;
function TJsonStringWriter.ToString:
string;
begin
Result := FStringBuilder.ToString;
end;
{ TJsonStringReader }
constructor TJsonStringReader.Create(
const AJson:
string);
begin
FStringReader := TStringReader.Create(AJson);
inherited Create(FStringReader);
end;
destructor TJsonStringReader.Destroy;
begin
FStringReader.Free;
inherited;
end;
end.