#1 2014-12-27 13:54:52

yurasek
Member
From: Belarus
Registered: 2011-04-19
Posts: 18

How to simply convert TSQLRecord > JSON > TSQLRecord?

I can not understand how the most simple to convert a lot of records SQLRecord to JSON, and then back again, but without the use of TSQLRestServerFullMemory?

I try so, but the first call SQLServiceState.FillOne returns False:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Mormot, StdCtrls, SynCommons;

type

  TSQLServiceState = class(TSQLRecord)
  private
    FState: Integer;
    FUpdated: Double;
  private
    property State: Integer read FState write FState;
    property Updated: Double read FUpdated write FUpdated;
  end;

  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

const
  Raws = 5;

var
  Form1: TForm1;
  JSON: RawUTF8;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  TextWriter: TTextWriter;
  i: Integer;
begin
  JSON:= '';
  Randomize;
  TextWriter:= TTextWriter.CreateOwnedStream;
  try
    for i:= 1 to Raws do
      TextWriter.AddJSONEscape(['Id', i, 'Updated', Now + Random(100), 'State', Random(100)]);
    JSON:= TextWriter.Text;
  finally
    TextWriter.Free
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  SQLServiceState: TSQLServiceState;
begin
  SQLServiceState:= TSQLServiceState.CreateAndFillPrepare(JSON);
  try
    while SQLServiceState.FillOne do //why False?
      begin
        Memo1.Lines.Add('Id : ' + IntToStr(SQLServiceState.ID));
        Memo1.Lines.Add('Updated : ' + DateTimeToStr(SQLServiceState.Updated));
        Memo1.Lines.Add('State : ' + IntToStr(SQLServiceState.State));
      end;
  finally
    SQLServiceState.Free;
  end;
end;

end.

Offline

#2 2014-12-27 15:02:52

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,659
Website

Re: How to simply convert TSQLRecord > JSON > TSQLRecord?

The content created in Button1Click is not a valid JSON array content.
Check http://json.org/
You need to add TextWriter.Add('[') before the loop, and TextWriter.Add(']') after it.

Offline

#3 2014-12-27 23:01:33

yurasek
Member
From: Belarus
Registered: 2011-04-19
Posts: 18

Re: How to simply convert TSQLRecord > JSON > TSQLRecord?

Thank you for your help.
I fixed code, now it works.
In the example I have one more mistake - I have the wrong published section for TSQLServiceState.

Offline

Board footer

Powered by FluxBB