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;

复制代码

三、显示结果如下:

不忘初心,如果您认为这篇文章有价值,认同作者的付出,可以微信二维码打赏任意金额给作者(微信号:382477247)哦,谢谢。

发布了382 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_18932003/article/details/105016371