[Lazarus] Convert record to JSON?

Bo Berglund bo.berglund at gmail.com
Fri Jul 20 19:33:19 CEST 2018


On Fri, 20 Jul 2018 20:09:25 +0300, AlexeyT via Lazarus
<lazarus at lists.lazarus-ide.org> wrote:

>
>> The config data are stored in a record and consists of a mix of data
>> types like strings and numbers as well as booleans.
>> Is there a simple way to encode the record as a JSON message
>
>Yes, it is. You can write to json values by path: /dir1/dir2/dir3/key,
>
>so for your record, make string paths for your values: /myrec/keybool ; 
>/myrec/keyint ; ...
>

I am not sure I understand your suggestion...

I was thinking something like this (based on an example in the wiki
(http://wiki.freepascal.org/Streaming_JSON):

type TMyRecord = record
    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; 
    reserved: array[0..18] of byte;
  end;


function RecToJSON(RC: TMyrecord): string;
var
  JS: TJSONStreamer;
begin
  JS := TJSONStreamer.Create(NIL);
  try
    JS.Options := JS.Options + [jsoTStringsAsArray];
    Result := JS.RecordToJSONString(RC);  //Seems not to exist...
  finally
    JS.Free;
  end;
end;

So I have two issues here:
1) It seems like there is no RecordToJSONString method only
ObjectToJSONString.

2) Do I have to convert my record to an object just to be able to use
JSON with it?

I want to avoid having to maintain a function where every member of
the record will be individually handled by name, then I don't gain
anything by going for JSON regarding future additions.
I want the output of the RecToJSON function to contain the field names
and current values of the record without ever changing this function
in the future when new fields are added....

Is this at all possible?

-- 
Bo Berglund
Developer in Sweden



More information about the Lazarus mailing list