Problem decoding JSON array

I have a simple procedure that creates a JSON array, then tries to extract an element from it.

This proc works

procedure TForm1.WebButton1Click(Sender: TObject);
var
  j: TJsonArray;
  o: TJsonObject;
  p: TJsonPair;
begin
  j := TJsonArray.Create;
  o := TJsonObject.Create;
  o.AddPair('Field1','Value1');
  j.Add(o);

  Memo.Lines.Add(j.ToJSON);
  o := j[0] as TJsonObject;
  Memo.Lines.Add(o.ToJSON);
  p := o.Pairs[0];
  showmessage(p.JsonValue.Value);
end;

it adds the following 2 lines to the memo

[{"Field1":"Value1"}]
{"Field1":"Value1"}

an the showmessage displays "Value1"

however, the following fails

procedure TForm1.WebButton1Click(Sender: TObject);
var
  j: TJsonArray;
  o: TJsonObject;
  p: TJsonPair;
begin
  j := TJsonArray.Create;
  o := TJsonObject.Create;
  o.AddPair('Field1','Value1');
  j.Add(o);

  Memo.Lines.Add(j.ToJSON);
  o := j[0] as TJsonObject;
  Memo.Lines.Add(o.ToJSON);
  showmessage(o.Values['Field1'].Value);
end;

with the error

Any ideas what I'm doing wrong ?

You may find this conversation useful.


Regards, Walter

Thanks for the link Walter.

It was an interesting read. I think it explains some of the issues I've been having. I've had to code around it by creating the JSON objects, then extracting it as a JSON string, then reparse it using TJsonObject.ParseJsonValue in order to create a collection of JSON objects that could be read using the pascal code. If I tried to access the initial JSON objects, they dont seem to be visible to pascal, but the ToJson method seems to have access to them.

I'd still be interested in hearing what TMS have to say.

Hello Andrew, you may find my JSON class helper useful.

JSON.pas (25.9 KB)

I wrote it because I found the existing implementation hopelessly buggy. I haven't rechecked if they fixed some bugs meanwhile though. This product luckily evolves quite fast.

Regards, Walter

We have fixed this issue. The next update will address this.