DelphiXe10对json的解析

Json语句

{"code":100,"state":"true","data":["hero","npc","pet"]}

引用单元

System.JSON  




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



Root.Count 获取Json对象数量



遍历对象名称及数值
for i:=0 to Root.count-1 do  
begin  
   memo1.lines.add(Root.Get(i).JsonString.toString + ' = ' + Root.Get(i).JsonValue.ToString);  
end;  


获取指定对象内数值
Root.GetValue('data').ToString  


获取数组对象
申明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遍历的方式读取数据比较稳妥。