#1 2022-07-18 15:16:54

edwinsn
Member
Registered: 2010-07-02
Posts: 1,218

'Variant method calls not supported' error when adding array

@ab,

I'm constructing a json object consists array of json objects, like the following:

{
	"MyItems": 
	[
		{
			"FileName": "111.txt",
			"Position": 0
		},
		{
			"FileName": "abc.exe",
			"Position": 1
		}
	]
}

Code for testing, and the 2 questions are written in the comments

procedure TForm4.btnTestAddArrayClick(Sender: TObject);
var
  i: Integer;
  itemVar: Variant;
  arrayVar: Variant;
  masterJson: Variant;
begin
  TDocVariant.New(arrayVar);
  TDocVariant.New(itemVar);
  TDocVariant.New(masterJson);

  for i := 0 to 1 do
  begin
    itemVar.FileName := 'file' + IntToStr(i);
    itemVar.Position := i;
    _Safe(arrayVar).AddItem(itemVar); // is there a better method for adding array item here?
  end;

  // the following two calls will cause 'Variant method calls not supported.' error, why?
  // masterJson.AddOrUpdateValue('ProjectItems', arrayVar);
  // masterJson.Value['ProjectItems'] := arrayVar;

  _Safe(masterJson).Value['MyArray'] := arrayVar; // ok

  ShowMessage(JSONReformat(VariantSaveJSON(masterJson)));
end;

Thanks for your help in advance!

Last edited by edwinsn (2022-07-18 15:17:50)


Delphi XE4 Pro on Windows 7 64bit.
Lazarus trunk built with fpcupdelux on Windows with cross-compile for Linux 64bit.

Offline

#2 2022-07-18 17:02:25

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

Re: 'Variant method calls not supported' error when adding array

You are making a confusing between variant and TDocVariantData.
AddOrUpdateValue or Value[] are part of TDocVariantData, not exposed as late-binding from the variant variable.

Please read the docs again.

Offline

#3 2022-07-19 02:35:33

edwinsn
Member
Registered: 2010-07-02
Posts: 1,218

Re: 'Variant method calls not supported' error when adding array

Oh I see.

masterJson.MyArray := arrayVar; 

equals to:

_Safe(masterJson).Value['MyArray'] := arrayVar;

Read the docs again and experimented again, I found that there are actually several ways to add an array of json objects to another json object wink

Thanks!


Delphi XE4 Pro on Windows 7 64bit.
Lazarus trunk built with fpcupdelux on Windows with cross-compile for Linux 64bit.

Offline

Board footer

Powered by FluxBB