首页 > 编程学习 > delphi JSON用法

delphi JSON用法

发布时间:2023/4/25 23:26:32

1、引用:uses TJSONObject;

1 json := TJSONObject.create;
2 json.addPair(‘姓名’,‘张三’);
3 json.addPair(‘年龄’,‘30’)
4 showmessage(json.tostring);//字符串格式
5 showmessage(json.tojson);// JSON格式
例子:

JSON语句:{“code”:100,“state”:“true”,“data”:[“hero”,“npc”,“pet”]}

2、引用单元:

System.JSON

3、类型说明:

//申明变量
Root:TJSONObject;
//赋值
Root:= TJSONObject.ParseJSONValue(Trim(JsonStr)) as TJSONObject;

4、获取JSON对象的数量

```cpp
Root.Count

5、遍历对象和数值

for i:=0 to Root.count-1 do
begin
   memo1.lines.add(Root.Get(i).JsonString.toString + ' = ' + Root.Get(i).JsonValue.ToString);
end;

结果显示:

"code" = 100
"state" = "true"
"data" = {"id":10,"name":"test"}

6、获取指定对象的数值:

Root.GetValue('data').ToString

7、获取数组对象:
申明json数组变量

Arr:TJSONArray;
Arr:=TJSONArray(Root.GetValue('data'));
遍历json数组
for i:=0 to Arr.Size - 1 do
begin
  memo1.lines.add(Arr.items[i].value);
end;

[---------------------------------第二示例-----------------------------------]
uses System.JSON;

procedure TForm1.Button1Click(Sender: TObject);
//解析JSON
begin
  var jo: TJSONObject := TJSONObject.ParseJSONValue('{"name":"张三", "other":["中国","程序员"]}') as TJSONObject;  //从字符串生成JSON
  Memo2.Lines.Add('遍历JSON数据:');
  Memo2.Lines.Add('JSON数据数量:' + IntToStr(jo.Count));
  var tmp: string;
  for var i: integer := 0 to jo.Count - 1 do    //1,遍历JSON数据
    tmp := tmp + jo.Get(i).ToString;
  Memo2.Lines.Add(tmp);
  Memo2.Lines.Add('');
  Memo2.Lines.Add('按元素解析JSON数据:');  //2,按元素解析JSON数据
  tmp := 'name = ' + jo.Values['name'].value;
  Memo2.Lines.Add(tmp);
  var ja: TJSONArray := TJSONArray(jo.GetValue('other'));   // json数组
  tmp := 'other = ' + jo.GetValue('other').ToString + #13#10; // 得到JSON数组字符串
  for var i: integer := 0 to ja.Size - 1 do    // 循环取得JSON数组中每个元素
    tmp := tmp + IntToStr(i + 1) + ' : ' + ja.Items[i].Value + #13#10;
  Memo2.Lines.Add(tmp);
  jo.Free;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
//生成JSON
begin
  var jo: TJSONObject := TJSONObject.Create;
  jo.AddPair('name','张三');
 // var ja: TJSONArray := TJSONObject.ParseJSONValue('["中国","程序员"]') as TJSONArray;
  var ja: TJSONArray := TJSONArray.Create;
  ja.Add('中国');
  ja.Add('程序员');
  jo.AddPair('other', ja);
  Memo2.Lines.Add(jo.ToString); //{"name":"张三","other":["中国","程序员"]}
  Memo2.Lines.Add(jo.ToJSON);   //{"name":"\u5F20\u4E09","other":["\u4E2D\u56FD","\u7A0B\u5E8F\u5458"]}
  jo.Free;
end;
Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号