我正在使用DBXJson解析一个名为的简单json文件,response.json
并在网格中显示其内容,但是只有网格的第一行才会填充数据,即使有更多行/数据要显示。我在下面的代码中使用自定义网格,但是我尝试使用标准stringgrid修改以下代码,并且表现出相同的行为。这是我用来解析响应并将其显示在网格中的代码。
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循环索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句