Delphi自代的JSON类TJSONObject_实例代码

实例代码:

Delphi自代的JSON类TJSONObject_实例代码_02Delphi自代的JSON类TJSONObject_json_03

 1 unit Unit1;
2
3 interface
4
5 uses
6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
7 Vcl.Controls, Vcl.Forms, Vcl.Dialogs
8 ,System.JSON //使用JSON就要引入这个
9 ,Vcl.StdCtrls
10 ;
11
12 type
13 TForm1 = class(TForm)
14 Button1: TButton;
15 Memo1: TMemo;
16 procedure Button1Click(Sender: TObject);
17 private
18 { Private declarations }
19 public
20 { Public declarations }
21 end;
22
23 var
24 Form1: TForm1;
25
26 implementation
27
28 {$R *.dfm}
29
30 procedure TForm1.Button1Click(Sender: TObject);
31 var
32 oJSON: TJSONObject;
33 I: Integer;
34 oJSONArray: TJSONArray;
35 oJSONPair: TJSONPair;
36 begin
37 oJSON := TJSONObject.ParseJSONValue(Trim('{"code":100,"state":"true","data":["hero","npc","pet"]}')) as TJSONObject;
38 //json节点数
39 Memo1.Lines.Add(IntToStr(oJSON.Count)); //3
40 //使用Index取出节点的“名字”“值”
41 for I:=0 to oJSON.count-1 do
42 begin
43 Memo1.Lines.Add(oJSON.Get(I).JsonString.toString + ' = ' +
44 oJSON.Get(I).JsonValue.ToString);
45 //"code" = 100 //"state" = "true" //"data" = ["hero","npc","pet"]
46 end;
47 //获得节点字符串
48 Memo1.Lines.Add(oJSON.Get('state').ToJSON);//"state":"true"
49 //使用name取出节点的“名字”“值”
50 Memo1.Lines.Add(oJSON.Get('state').JsonString.Value); //state
51 Memo1.Lines.Add(oJSON.Get('state').JsonValue.Value);//true
52 Memo1.Lines.Add(oJSON.Get('state').JsonString.ToString);//"state"
53 Memo1.Lines.Add(oJSON.Get('state').JsonValue.ToString); //"true"
54 //使用name取出节点的“值”
55 Memo1.Lines.Add(oJSON.GetValue('state').ToString);//"true"
56 //修改节点的“值”
57 oJSON.Get('state').JsonValue := TJSONString.Create('dddd');
58 //移除一个节点
59 oJSON.RemovePair('state');
60 //增加一个节点
61 oJSON.AddPair('state', 'eeeeee');
62 //遍历json数组
63 oJSONArray := TJSONArray(oJSON.GetValue('data'));
64 for I:=0 to oJSONArray.Size - 1 do
65 begin
66 Memo1.Lines.Add(oJSONArray.Items[I].Value); //hero //npc //pet
67 end;
68 //使用index获取节点
69 oJSONPair := oJSON.Pairs[0];
70 Memo1.Lines.Add(oJSONPair.JsonString.Value);//code
71 Memo1.Lines.Add(oJSONPair.JSONValue.Value);//100
72 Memo1.Lines.Add(oJSONPair.JsonString.ClassName);//TJSONString
73 Memo1.Lines.Add(oJSONPair.JsonValue.ClassName);//TJSONNumber
75 oJSON.Free;
76 end;
77
78 end.

View Code