delphi 自带JSON的用法


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对象的数量

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;

Json解析无法判断数据内是否存在指定对象名,所以在吃不准是否存在指定对象的时候,还是使用get遍历的方式读取数据比较稳妥。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM