unit Bcl.Json;

interface

uses
  Rtti, Classes,
  Bcl.Json.Converters,
  Bcl.Json.Serializer,
  Bcl.Json.Deserializer;

type
  TJson = class
  public
    class function Serialize(const Value: TValue): string; overload;
    class function SerializeAs<T>(const Value: T): string; overload;
    class procedure Serialize(const Value: TValue; Stream: TStream); overload;
    class procedure SerializeAs<T>(const Value: T; Stream: TStream); overload;


    class function Deserialize<T>(const Json: string): T; overload;
    class function Deserialize(const Json: string; const ATypeToken: TTypeToken): TValue; overload;
    class function Deserialize<T>(Stream: TStream): T; overload;
    class function Deserialize(Stream: TStream; const ATypeToken: TTypeToken): TValue; overload;
  end;

implementation

{ TJson }

class function TJson.Serialize(const Value: TValue): string;
var
  Serializer: TJsonSerializer;
begin
  Serializer := TJsonSerializer.Create;
  try
    Result := Serializer.Write(Value);
  finally
    Serializer.Free;
  end;
end;

class function TJson.SerializeAs<T>(const Value: T): string;
begin
  Result := Serialize(TValue.From<T>(Value));
end;

class function TJson.Deserialize(const Json: string;
  const ATypeToken: TTypeToken): TValue;
var
  Deserializer: TJsonDeserializer;
begin
  Deserializer := TJsonDeserializer.Create;
  try
    Result := Deserializer.Read(Json, ATypeToken);
  finally
    Deserializer.Free;
  end;
end;

class function TJson.Deserialize(Stream: TStream;
  const ATypeToken: TTypeToken): TValue;
var
  Deserializer: TJsonDeserializer;
begin
  Deserializer := TJsonDeserializer.Create;
  try
    Result := Deserializer.Read(Stream, ATypeToken);
  finally
    Deserializer.Free;
  end;
end;

class function TJson.Deserialize<T>(const Json: string): T;
begin
  Result := Deserialize(Json, TypeInfo(T)).AsType<T>;
end;

class function TJson.Deserialize<T>(Stream: TStream): T;
begin
  Result := Deserialize(Stream, TypeInfo(T)).AsType<T>;
end;

class procedure TJson.Serialize(const Value: TValue; Stream: TStream);
var
  Serializer: TJsonSerializer;
begin
  Serializer := TJsonSerializer.Create;
  try
    Serializer.Write(Value, Stream);
  finally
    Serializer.Free;
  end;
end;

class procedure TJson.SerializeAs<T>(const Value: T; Stream: TStream);
begin
  Serialize(TValue.From<T>(Value), Stream);
end;

end.