简体   繁体   中英

How to count number of elements in a JSON array in Delphi

I am accessing a TJSONValue in Delphi(using REST components and Google Books' API). I want to know how many elements are in the array: 'items'. This is the format of the JSONValue:

  "kind": "books#volumes", "totalItems": 221, "items": [ {...}, {...}, {...}] 

Note* "totalItems" does not refer to the size of the array.

I've tried somethin along this line, but it raises a conversion error.

var
   JSONBook: TJSONValue;
   CountItems: integer;
begin
   JSONBook := RESTResponse1.JSONValue;

   ShowMessage(IntToStr(JSONBook.GetValue<string>('items').Length));
   CountItems := JSONBook.GetValue<string>('items').Length;

   for i := 0 to CountItems-1 do
   begin
     ...
   end;
end;

The items field is an array, so retrieving it as a string is just wrong, so it makes sense that reading the array count via a string length would not work.

Try this instead:

uses
  ..., System.JSON;

var
  JSONBook, JSONItem: TJSONObject;
  JSONItems: TJSONArray;
  CountItems: integer;
begin
  JSONBook := RESTResponse1.JSONValue as TJSONObject;
  JSONItems := JSONBook.GetValue('items') as TJSONArray;

  CountItems := JSONItems.Count;
  ShowMessage(IntToStr(CountItems));

  for i := 0 to CountItems-1 do
  begin
    JSONItem := JSONItems.Items[i] as TJSONObject;
    ...
  end;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM