0

This works, when it is an object:

{"data":{"url":"stackoverflow.com"}}

This does not work, when it is an array:

{"data":[{"url":"stackoverflow.com"}]}

Error: Invalid class typecast

procedure TForm1.Button1Click(Sender: TObject);
var
  json : string;
  obj, data : TJSONObject;
  url : string;

begin
  json := '{"data":{"url":"stackoverflow.com"}}';
  obj := TJSonObject.ParseJSONValue(json) as TJSONObject;

  try
    data := obj.Values['data'] as TJSONObject;
    url := data.Values['url'].value;
    showMessage(url);
  finally
    obj.Free;
  end;
end;

I know I have to use TJSONArray, but I don't know how to implement it.

0

1 Answer 1

2

This is not hard to understand.

In the first case, the value of data is an object, so obj.Values['data'] as TJSONObject is correct.

In the second case, the value of data is an array, so obj.Values['data'] as TJSONObject is wrong. it needs to be obj.Values['data'] as TJSONArray instead, and then you access the TJSONObject from the elements of the array, eg:

procedure TForm1.Button1Click(Sender: TObject);
var
  json : string;
  obj, data : TJSONObject;
  arr: TJSONArray;
  url : string;

begin
  json := '{"data":[{"url":"stackoverflow.com"}]}';
  obj := TJSonObject.ParseJSONValue(json) as TJSONObject;

  try
    arr := obj.Values['data'] as TJSONArray;
    data := arr[0] as TJSONObject;
    url := data.Values['url'].Value';
    ShowMessage(url);
  finally
    obj.Free;
  end;
end;
Sign up to request clarification or add additional context in comments.

1 Comment

Now I see it, pass it to an array and then access that position. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.