我正在 Delphi 中访问 TJSONValue(使用 REST 组件和 Google Books 的 API)。我想知道数组中有多少个元素:'items'。 这是 JSONValue 的格式:
"kind": "books#volumes", "totalItems": 221, "items": [ {...}, {...}, {...}]
注意*“totalItems”不是指数组的大小。
我已经沿着这条线尝试了一些东西,但它引发了一个转换错误。
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;
最佳答案
items
字段是一个数组,因此将其作为 string
检索是错误的,因此通过字符串长度读取数组计数是行不通的.
试试这个:
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;
关于arrays - 如何计算 Delphi 中 JSON 数组中元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199209/