Delphi使用json填充stringgrid
时间: 2024-05-05 18:16:25 浏览: 214
以下是在Delphi中使用JSON填充StringGrid的示例代码:
```delphi
uses
System.JSON;
procedure TForm1.FillStringGridWithJSON(JSONString: string; StringGrid: TStringGrid);
var
JSONArray: TJSONArray;
JSONObject: TJSONObject;
JSONValue: TJSONValue;
i, j: Integer;
begin
JSONArray := TJSONObject.ParseJSONValue(JSONString) as TJSONArray;
try
StringGrid.RowCount := JSONArray.Count + 1;
StringGrid.ColCount := JSONArray.Items[0].Count;
for i := 0 to JSONArray.Count - 1 do
begin
JSONObject := JSONArray.Items[i] as TJSONObject;
for j := 0 to JSONObject.Count - 1 do
begin
JSONValue := JSONObject.Pairs[j].JsonValue;
StringGrid.Cells[j, i+1] := JSONValue.Value;
end;
end;
finally
JSONArray.Free;
end;
end;
```
使用方法:
1. 将上述代码添加到您的Delphi窗体或数据模块中。
2. 调用FillStringGridWithJSON函数,将JSON字符串和要填充的StringGrid作为参数传递。
3. JSON字符串应该包含一个JSON数组,其中每个元素是一个JSON对象,每个JSON对象包含要填充到StringGrid中的数据。
示例JSON字符串:
```json
[
{"Name": "John", "Age": 30, "City": "New York"},
{"Name": "Jane", "Age": 25, "City": "Los Angeles"},
{"Name": "Bob", "Age": 40, "City": "Chicago"}
]
```
示例代码调用:
```delphi
FillStringGridWithJSON('[{"Name": "John", "Age": 30, "City": "New York"}, {"Name": "Jane", "Age": 25, "City": "Los Angeles"}, {"Name": "Bob", "Age": 40, "City": "Chicago"}]', StringGrid1);
```
注意:在使用JSON填充StringGrid时,需要确保StringGrid的RowCount和ColCount足够容纳所有数据。如果数据超出了行数或列数,将会引发错误。
阅读全文
相关推荐







