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