[Lazarus] Convert record to JSON?

Michael Van Canneyt michael at freepascal.org
Sat Jul 21 09:29:29 CEST 2018



On Fri, 20 Jul 2018, Bo Berglund via Lazarus wrote:

> On Fri, 20 Jul 2018 19:33:19 +0200, Bo Berglund via Lazarus
> <lazarus at lists.lazarus-ide.org> wrote:
>
> I changed my code now so my recrd is instead an object:
>
> type TMyRecord = Class(TObject)
>    checksum: word;
>    ssid: AnsiString;
>    passwd: AnsiString;
>    macaddr: AnsiString;
>    addr: TIpAddress;
>    baud: integer;
>    tcpport: word;
>    mode: byte;
>    channel: byte;
>    hidden: byte;  // hidden (1) or visible (0)
>    fixedaddress: byte; //Station mode fixed addr instead of DHCP
>    numsensors: byte; //Number of active DHT sensors (0..3)
>    dhtinterval: word;  // Interval between DHT sensor readings (min)
>    host: AnsiString;
>  end;
>
> I also changed my function to create the JSON string:
>
> function RecToJSON(RC: TMyrecord): string;
> var
>  JS: TJSONStreamer;
> begin
>  JS := TJSONStreamer.Create(NIL);
>  try
>    JS.Options := JS.Options + [jsoTStringsAsArray];
>    Result := JS.ObjectToJSONString(RC);
>  finally
>    JS.Free;
>  end;
> end;
>
> When I run this code in my existing application I can step into the
> line
>   Result := JS.ObjectToJSONString(RC);
> and hover the mouse over RC and it displays the correct values for all
> fields of the object.
>
> But when the line executes the result is a string with only this empty
> content:
>
> {}
>
> Why is this?
> What have I done wrong?

Because RTTI is made only for published properties.

So, you must make it published properties:

Type

{ needed if you want to descend from TObject.
   You can also descend from TPersistent. }

{$M+}
   TMyRecord = Class(TObject)
   Published
     Property checksum: word Read FChecksum Write FCheckSum;
     // etc.
   end;

Michael.


More information about the Lazarus mailing list