unit XData.Json.Deserializer;

{$I XData.Inc}

interface

uses
  XData.Json.Converter,
  Bcl.Json.Converters,

  XData.Json.Solver,
  Bcl.Json.Deserializer,
  Bcl.Json.Reader,
  XData.Model.Classes,
  XData.Aurelius.Model,
  XData.Json.Converters;

type
  TXDataJsonClientDeserializer = class(TJsonDeserializer)
  private
    FConverters: TXDataJsonConverters;
  public
    constructor Create(AModel: TXDataAureliusModel;
      ASolver: IJsonReferenceSolver);
    destructor Destroy; override;
    function CreateObject(Reader: TJsonReader; BaseType: TXDataEntityType): TObject; overload;
  end;

  TXDataJsonServerDeserializer = class(TJsonDeserializer)
  private
    FConverters: TXDataJsonConverters;
  public
    constructor Create(AModel: TXDataAureliusModel;
      ASolver: IJsonReferenceSolver);
    destructor Destroy; override;
    function CreateObject(Reader: TJsonReader; BaseType: TXDataEntityType): TObject; overload;
    procedure SetUnknownMemberHandling(Value: TUnknownMemberHandling);
  end;

implementation

uses
  XData.Consts;

{ TXDataJsonClientDeserializer }

constructor TXDataJsonClientDeserializer.Create(AModel: TXDataAureliusModel;
  ASolver: IJsonReferenceSolver);
begin
  FConverters := TXDataJsonConverters.Create(AModel);
  FConverters.EntityFactory.ProxyControllerOnReferences := true;
  FConverters.EntityFactory.IgnoreProxies := false;
  FConverters.EntityFactory.IgnoreBlobProxies := false;
  FConverters.EntityFactory.Solver := ASolver;
  inherited Create(FConverters, False);
end;

function TXDataJsonClientDeserializer.CreateObject(Reader: TJsonReader;
  BaseType: TXDataEntityType): TObject;
begin
  if BaseType <> nil then
    Result := Read(Reader, BaseType.Data.AsType<TClass>).AsObject
  else
    Result := Read<TObject>(Reader);
end;

destructor TXDataJsonClientDeserializer.Destroy;
begin
  FConverters.Free;
  inherited;
end;

{ TXDataJsonServerDeserializer }

constructor TXDataJsonServerDeserializer.Create(AModel: TXDataAureliusModel;
  ASolver: IJsonReferenceSolver);
begin
  FConverters := TXDataJsonConverters.Create(AModel);
  FConverters.EntityFactory.Solver := ASolver;
  FConverters.EntityFactory.ProxyControllerOnReferences := False;
  FConverters.EntityFactory.IgnoreProxies := False;
  FConverters.EntityFactory.IgnoreBlobProxies := true;
  inherited Create(FConverters, False);
end;

function TXDataJsonServerDeserializer.CreateObject(Reader: TJsonReader;
  BaseType: TXDataEntityType): TObject;
begin
  if BaseType <> nil then
    Result := Read(Reader, BaseType.Data.AsType<TClass>).AsObject
  else
    Result := Read<TObject>(Reader);
end;

destructor TXDataJsonServerDeserializer.Destroy;
begin
  FConverters.Free;
  inherited;
end;

procedure TXDataJsonServerDeserializer.SetUnknownMemberHandling(
  Value: TUnknownMemberHandling);
begin
  FConverters.EntityFactory.UnknownMemberHandling := Value;
end;

end.

