delphi json

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    mmo1: TMemo;
    mmo2: TMemo;
    btn3: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn3Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);

  private

  public


  end;

var
  Form1: TForm1;

const
  // 演示用的JSON
  jsonString = '{"name":"张三", "other":["中国","程序员"]}';

implementation

{$R *.dfm}

uses
  System.json; // Dephi自带的JSON单元

procedure TForm1.btn1Click(Sender: TObject);
var
  JSONObject: TJSONObject; // JSON类
  i: Integer; // 循环变量
  temp: string; // 临时使用变量
  jsonArray: TJSONArray; // JSON数组变量
begin
  if Trim(mmo1.Text) = '' then
  begin
    ShowMessage('要解析数据不能为空!');
  end
  else
  begin
    JSONObject := nil;
    try
      { 从字符串生成JSON }
      JSONObject := TJSONObject.ParseJSONValue(Trim(mmo1.Text)) as TJSONObject;
      if JSONObject.Count > 0 then
      begin
        { 1,遍历JSON数据 }
        mmo2.Lines.Add('遍历JSON数据:' + #13#10);
        mmo2.Lines.Add('JSON数据数量:' + IntToStr(JSONObject.Count));
        for i := 0 to JSONObject.Count - 1 do
        begin
          if i = 0 then
          begin
            temp := JSONObject.Get(i).ToString + #13#10;;
          end
          else
          begin
            temp := temp + JSONObject.Get(i).ToString + #13#10;
          end;
        end;
        { output the JSON to console as String }
        mmo2.Lines.Add(temp);
        mmo2.Lines.Add('------------------------------');



        { 2,按元素解析JSON数据 }
        mmo2.Lines.Add('按元素解析JSON数据:' + #13#10);
        temp := 'name = ' + JSONObject.Values['name'].ToString + #13#10;
        mmo2.Lines.Add(temp);

        // json数组
        jsonArray := TJSONArray(JSONObject.GetValue('other'));;
        if jsonArray.Count > 0 then
        begin
          // 得到JSON数组字符串
          temp := 'other = ' + JSONObject.GetValue('other').ToString + #13#10;
          // 循环取得JSON数组中每个元素
          for i := 0 to jsonArray.Size - 1 do
          begin
            temp := temp + IntToStr(i + 1) + ' : ' + jsonArray.Items[i]
              .Value + #13#10;
          end;
        end;
        mmo2.Lines.Add(temp);
      end
      else
      begin
        temp := '没有数据!';
        mmo2.Lines.Add(temp);
      end;

    finally
      JSONObject.Free;
    end;
  end;


end;
procedure TForm1.btn2Click(Sender: TObject);
begin
  mmo1.Text := '';
  mmo2.Text := '';
end;


// 设置要解析的JSON数据
procedure TForm1.btn3Click(Sender: TObject);
begin
  mmo1.Text := jsonString;
end;


// 设置要解析的JSON数据
procedure TForm1.FormCreate(Sender: TObject);
begin
  mmo1.Text := jsonString;
end;


end.
posted @ 2020-01-09 14:59  创新创造学习整合套路  阅读(263)  评论(0编辑  收藏  举报