- 人气:
- 放大
- 缩小
- 二维码
- 赞赏
delphi10.3读取JSON数据
Delphi10.3读取JSON数据
一、我们有一段JSON数据如下:
复制代码
{
"五班": [
{
"姓名": "张三",
"成绩": 75.5
},
{
"姓名": "李四",
"成绩": 21.7
}
]
}
复制代码
二、使用Delphi代码读取,代码如下:
复制代码
uses
System.Types,
System.JSON,
System.JSON.Types,
System.JSON.Writers,
System.JSON.Builders;
procedure TForm1.Button4Click(Sender: TObject);
var
I: Integer;
m_JsonStr: string;
m_SubArray: TJSONArray;
m_JsonObject: TJSONObject;
m_SubJsonObj: TJSONObject;
begin
// 读取JSON文件
m_JsonStr := Trim(Memo1.Text);
m_JsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(m_JsonStr), 0) as TJSONObject;
// 取最外层
for I := 0 to m_JsonObject.count - 1 do
begin
Memo2.Lines.Add(m_JsonObject.Get(I).JsonString.toString + ' = ' + m_JsonObject.Get(I).JsonValue.ToString);
end;
// 取内层
m_SubArray := m_JsonObject.getValue('五班') as TJSONArray;
for I := 0 to m_SubArray.size - 1 do
begin
m_SubJsonObj := m_SubArray.Get(I) as TJSONObject;
Memo2.Lines.Add(Format('标签:%s = %s', [m_SubJsonObj.Get(0).JsonString.ToString, m_SubJsonObj.Get(0).JsonValue.ToString]));
Memo2.Lines.Add(Format('标签:%s = %s', [m_SubJsonObj.Get(1).JsonString.ToString, m_SubJsonObj.Get(1).JsonValue.ToString]));
end;
end;