我正在使用 DBXJson 解析一个名为 response.json
的简单 json 文件,并在网格中显示其内容,但只有网格的第一行填充了数据,即使有是要显示更多行/数据。我在下面的代码中使用了自定义网格,但我尝试了使用标准字符串网格的下面代码的变体,它表现出了相同的行为。这是我用来解析响应并将其显示在网格中的代码。
var
sl: TStringList;
LJsonArr: TJSONArray;
LJsonValue: TJSONValue;
LItem: TJSONValue;
col, row: Integer;
begin
col := 0;
row := 0;
sl := TStringList.Create;
sl.LoadFromFile('response.txt');
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sl.text), 0)
as TJSONArray;
for LJsonValue in LJsonArr do
begin
NextGrid1.AddRow();
for LItem in TJSONArray(LJsonValue) do
begin
NextGrid1.Cells[col, row] := TJSONPair(LItem).JsonValue.Value;
inc(col);
end;
inc(row);
end;
sl.Free;
end;
我怀疑问题在于 row
变量不合适并且没有被调用,这导致只显示第一行,但我可能会弄错,我我希望有一双新的眼睛能够发现问题。
最佳答案
问题是每次开始新行时,col
都必须重新初始化为零。因此将 col
的初始化移到外循环中。
row := 0;
for LJsonValue in LJsonArr do
begin
col := 0;
NextGrid1.AddRow();
for LItem in TJSONArray(LJsonValue) do
begin
NextGrid1.Cells[col,row] := TJSONPair(LItem).JsonValue.Value;
inc(col);
end;
inc(row);
end;
我不知道这个 JSON 库,但如果它允许您通过随机访问来访问数组元素,那么传统的 oindexed for 循环将导致比您使用的 for in 循环更干净的代码。在伪代码中:
for row := 0 to arr.length do
begin
item := arr[row];
for col := 0 to item.length do
grid.Cells[col,row] := item[col];
end;
根据经验,如果您不需要知道项目索引,则 for in 循环会更好。然而,一旦您需要知道项目索引,那么传统的索引 for 循环通常是首选。
关于delphi - for循环中的变量没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459098/