#1 2025-03-11 06:24:21

ertank
Member
Registered: 2016-03-16
Posts: 178

Json - Passing Variant a record

Hello,

There is a situation where I need to conditionally send json value as null or as a record to a server. Since there is null involved, I declared my record using variant for that specific variable.
Problem is, I couldn't figure out a way to pass a record to variant. I tried to pass a string like below (actual record is more complex than the example).

type
  TRec = packed record
    int: Integer;
    Val: Variant; // sometimes NULL sometimes a record
  end;

  TRec2 = packed record
    Percentage: Double;
  end;

procedure TForm1.FormCreate(Sender: TObject);
var
  LRec: TRec;
  LRec2: TRec2;
  LRecJson, LRec2Json: string;
begin
  LRec2.Percentage := 1.5;
  LRec2Json := string(mormot.core.json.RecordSaveJson(LRec2, TypeInfo(TRec2)));

  LRec.int := 123;
  LRec.Val := LRec2Json;
  LRecJson := string(mormot.core.json.RecordSaveJson(LRec, TypeInfo(TRec)));
end;

Above code results below json string in LRecJson where Val contains a string value.

{"int":123,"Val":"{\"Percentage\":1.5}"}

What I am trying to achieve is to have Val contain a json object as below

{"int":123,"Val":{"Percentage":1.5}}

Is this possible using mORMot2 and records?

Thanks & Regards,
Ertan

Offline

#2 2025-03-11 07:01:06

itSDS
Member
From: Germany
Registered: 2014-04-24
Posts: 544

Re: Json - Passing Variant a record

May be its better to use TObject instead of record than null in val should be possible


Rad Studio 12.3 Athens

Offline

#3 2025-03-11 11:15:23

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

Re: Json - Passing Variant a record

You are making a confusion between variant types.

If you set

LRec.Val := LRec2Json;

then you are setting a string to the Val property, and it is serialized as such.

You need to write a TDocVariant instance explicitely, e.g. as:

LRec.Val := _JsonFast(LRec2Json);

Offline

#4 2025-03-11 14:12:12

ertank
Member
Registered: 2016-03-16
Posts: 178

Re: Json - Passing Variant a record

I was trying to learn how to do it. That _JsonFast() is working just fine.

Thank you

Offline

Board footer

Powered by FluxBB