Delphi中Json格式读写

时间:2023-03-08 21:40:53

Json是一种轻量级传输数据格式,广泛应用互联网和各应用中。json主要採用键值对来表示数据项。多个数据项之间用逗号分隔,也能够用于数组。以下注重介绍一下在delphi中使用json,在delphi中使用json经常使用superobject单元文件。该文件能够在网上下载,最初接触json是在2011年,好久没用这不刚好有项目要用到又折腾了好久,以下做了一个简单的Demo,方便以后忘了能随时查看。详细的json使用能够參看万一老师的博客,记录的非常详细,以下的demo主要是将数据库记录转换为json格式,然后进行解析。详细源代码例如以下。

新建一个delphi应用程序,在窗口上放置table组件,连接数据DBDEMOS。连接表customer.db,active设置为true。

详细文件例如以下:

delphiproject文件例如以下

program Project1;

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

单元文件例如以下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Grids, DBGrids, DB, DBTables;

type
  TForm1 = class(TForm)
    mmo1: TMemo;
    tbl1: TTable;
    ds1: TDataSource;
    btn1: TButton;
    btn2: TButton;
    btn3: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses  superobject;

procedure TForm1.btn1Click(Sender: TObject);
var
  jo,jt:ISuperObject;
begin
  jo:=SO();
  jt:=SO();
  jo.S['xm']:='张三';
  jo.I['age']:=25;
  jo.S['sex']:='男';
  jt.O['person']:=jo;
  ShowMessage(jt.AsString);
  ShowMessage(jt.O['person'].S['xm']);
end;

procedure TForm1.btn2Click(Sender: TObject);
var
  i:Integer;
  jfields,jitems,jo:ISuperObject;
begin
  mmo1.Clear;
  jitems:=SA([]);
  jo:=SO();
  with tbl1 do
  begin
    First;
    while not eof do
    begin

      jfields:=SO();
      for i:=0 to FieldCount-1 do
      begin
        if Fields[i].DataType=ftDateTime then
         jfields.S[Fields[i].FieldName]:=FormatDateTime('yyyy-mm-dd hh:mm:ss',Fields[i].AsDateTime)
        else
         jfields.S[Fields[i].FieldName]:=Fields[i].AsString;
      end;
      jitems.AsArray.Add(jfields);
      Next;
    end;
  end;
  jo.O['records']:=jitems;
  mmo1.Lines.Add(jo.AsString);
end;

procedure TForm1.btn3Click(Sender: TObject);
var
  jo,m:ISuperobject;
  i,j:Integer;
  tt:TSuperArray;
  s:string;
  lst:TStringList;
begin
  if mmo1.Text<>'' then
  begin
    lst:=TStringList.Create;
    jo:=so(mmo1.Text);
    tt:=jo.O['records'].AsArray;
    for i:=0 to tt.Length-1 do
    begin
      s:='';
      for j:=0 to tbl1.FieldCount-1 do
      begin
       if s='' then
        s:=tt.O[i].S[tbl1.Fields[j].FieldName]
       else
        s:=s+' '+tt.O[i].S[tbl1.Fields[j].FieldName]
      end;
      lst.Add(s);
    end;
    ShowMessage(lst.Text) ;
    lst.Free;
  end;
end;

end.

dfm文件例如以下:

object Form1: TForm1
  Left = 312
  Top = 70
  Width = 410
  Height = 382
  Caption = 'json读写'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object mmo1: TMemo
    Left = 0
    Top = 0
    Width = 394
    Height = 249
    Align = alTop
    TabOrder = 0
  end
  object btn1: TButton
    Left = 23
    Top = 264
    Width = 75
    Height = 25
    Caption = '简单读写'
    TabOrder = 1
    OnClick = btn1Click
  end
  object btn2: TButton
    Left = 121
    Top = 264
    Width = 105
    Height = 25
    Caption = '读数据库记录'
    TabOrder = 2
    OnClick = btn2Click
  end
  object btn3: TButton
    Left = 253
    Top = 263
    Width = 75
    Height = 25
    Caption = '解析json'
    TabOrder = 3
    OnClick = btn3Click
  end
  object tbl1: TTable
    Active = True
    DatabaseName = 'DBDEMOS'
    TableName = 'customer.db'
    Left = 288
    Top = 152
  end
  object ds1: TDataSource
    DataSet = tbl1
    Left = 104
    Top = 176
  end
end

当中有些版本号superobject的hash方法有编译指令,我使用时报错,将其去掉改为例如以下:

class function TSuperAvlEntry.Hash(const k: SOString): Cardinal;
var
  h: cardinal;
  i: Integer;
begin
  h := 0;
  for i := 1 to Length(k) do
    h := h*129 + ord(k[i]) + $9e370001;
  Result := h;
end;

程序执行结果例如以下:

Delphi中Json格式读写

点击简单读写

Delphi中Json格式读写

Delphi中Json格式读写

读数据库记录

Delphi中Json格式读写

解析jsonDelphi中Json格式读写

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhlbmdodWkx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

superobject单元还提供了很多方法,在此不一一列举使用,以后使用中再慢慢总结。