Delphi Rest.JSON do not work on simple class

Viewed 117

I am working on my main project and I have to "JSON serialize" a simple class :


  TServer = class
  public
    Host: string;
  end;

  TServerList = class
  public
    Servers: TArray<TServer>;
  end;

procedure Test;
begin
  var SrvLst := TServerList.Create;
  SetLength(SrvLst.Servers, 1);
  SrvLst.Servers[0] :=  TServer.Create;
  SrvLst.Servers[0].Host := 'TEST';

  var Json := TJson.ObjectToJsonString(SrvLst);
  // >> Json = '{"servers":[{"host":"TEST"}]}' , it works...
  var SrvLst2 := TJson.JsonToObject<TServerList>(Json);
  // >> SrvLst2.Server is empty ?? what's wrong ??

  // memory leaks.. nevermind
end;

I can't see what is wrong... Any idea ? Thank you.

1 Answers

You need to either declare the classes this way:

  TServer = class
  private
    FHost: string;
  public
    property Host: string read FHost write FHost;
  end;

  TServerList = class
  private
    FServers: TArray<TServer>;
  public
    property Servers: TArray<TServer> read FServers write FServers;
  end;

or this way:

type
  TServer = class
  public
    [JSONName('Host')]
    Host: string;
  end;

  TServerList = class
  public
    [JSONName('Servers')]
    Servers: TArray<TServer>;
  end;

Note that the latter requires to use REST.Json.Types.

Related