如何计算 JsonArray 中的项目数量(Delphi)

问题描述 投票:0回答:1

我正在使用 Json 迈出第一步,我正在寻找一种解决方案来获取 JasonArray 中的项目数量。 我需要在 For 循环中计数的数字。

以下代码对我有用,只是现在设置为 5 的计数应该是 替换为数组中的项目数。已经尝试过 JsonArray.Count -1 根据我的研究应该是正确的方法,但只需用 JsonArray.Count -1 替换数字就会导致 访问冲突。

var
   JSonObject:TJSonObject;
   JSonValue:TJSonValue;
   JSOnArray:TJsonArray;
   st:string;
   id, name, description,sku,price: string;
   i,j: integer;


begin
st := memo1.Text;

j := 1;
if Assigned(JSONArray) then
begin

For i := 0 to 5 -1 do
Begin
   JSonObject := TJSonObject.Create;
   JsonValue:=JSonObject.ParseJSONValue(st);
   if (JSONValue is TJSONArray) then
   Begin
    id := ((JSONValue as TJSONArray).Items[i] as TJSonObject).Get('id').JSONValue.Value;
    sku := ((JSONValue as TJSONArray).Items[i] as TJSonObject).Get('sku').JSONValue.Value;
    description := ((JSONValue as TJSONArray).Items[i] as TJSonObject).Get('description').JSONValue.Value;
    name := ((JSONValue as TJSONArray).Items[i] as TJSonObject).Get('name').JSONValue.Value;
    price := ((JSONValue as TJSONArray).Items[i] as TJSonObject).Get('price').JSONValue.Value;
    stringgrid1.Cells[1,j] := sku;
    stringgrid1.Cells[2,j] := name;
    stringgrid1.Cells[4,j] := description;
    stringgrid1.Cells[3,j] := price;
   j:=j+1;
   End;
End;

JSonObject.Free;
end;

arrays json delphi
1个回答
0
投票

JsonArray.Count
是正确使用的值。然而,访问冲突是因为
JsonArray
未分配。您需要先解析 JSON,然后才能访问其内容。

此外,你的

for
循环是无用的,你只是一遍又一遍地重新解析相同的 JSON。

此外,您不需要创建

TJSONObject
实例来调用
ParseJSONValue()
,因为它是一个
class static
方法。

© www.soinside.com 2019 - 2024. All rights reserved.