我正在使用 JSON 迈出第一步,我正在寻找一种解决方案来获取
TJSONArray
中的项目数量。我需要在 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;
JsonArray.Count
是正确使用的值。但是,访问冲突是因为当您评估 JsonArray
循环时,for
是 未分配。按照您编码的方式,您的
for
循环会一遍又一遍地重新解析相同的 JSON,然后每次访问不同的数组元素。 这就是为什么当您对计数进行硬编码时代码不会崩溃。
您需要在运行循环之前解析 JSON。不要解析循环中的 JSON inside。
此外,您不需要创建TJSONObject
实例来调用
ParseJSONValue()
,因为它是一个
class static
方法。尝试更像这样的事情:
var
JSonObject: TJSonObject;
JSonValue: TJSonValue;
JSonArray: TJsonArray;
id, name, description, sku, price: string;
i, j: integer;
begin
JsonValue := TJSONObject.ParseJSONValue(Memo1.Text);
if Assigned(JsonValue) then
try
JSonArray := JsonValue as TJSONArray;
j := 1;
for i := 0 to JSonArray.Count-1 do
begin
JSonObject := JSonArray.Items[i] as TJSonObject;
id := JSonObject.GetValue('id').Value;
sku := JSonObject.GetValue('sku').Value;
description := JSonObject.GetValue('description').Value;
name := JSonObject.GetValue('name').Value;
price := JSonObject.GetValue('price').Value;
StringGrid1.Cells[1,j] := sku;
StringGrid1.Cells[2,j] := name;
StringGrid1.Cells[3,j] := price;
StringGrid1.Cells[4,j] := description;
Inc(j);
end;
finally
JsonValue.Free;
end;
end;