Xe7 System.Json解析数据格式
{"code":1,"msg":"","data":{"GradeInfo":[{"gradeid":1,"gradename":"普通介绍人","graderate":0.02}],"UserList":[{"stype":"User","userid":"119110"},{"stype":"User","userid":"11911044"},{"stype":"User","userid":"119110444"},{"stype":"User","userid":"121121"},
{"stype":"User","userid":"13211111113"},{"stype":"User","userid":"abcadsfa"},{"stype":"Customer","userid":"admin"},{"stype":"Shoper","userid":"Shop2222"}]}}
var
Jsobj:TJSONObject;
i,j:Integer;
Jarr:TJSONArray;
temp:string;
v:string;
Jsvalue:Tjsonvalue ; begin Jsobj:=TJSONObject.ParseJSONValue(Memo1.Text) as TJSONObject;
temp:=Jsobj.GetValue('data').ToString;
Jsobj:=TJSONObject.ParseJSONValue(temp) as TJSONObject; jarr := TJSONArray(Jsobj.GetValue('UserList'));
for i := to Jarr.Size- do
begin
v:=(Jarr.Items[i].ToString);
Jsobj:=TJSONObject.ParseJSONValue(v) as TJSONObject;
// for j := 0 to Jsobj.Count do
// begin
ShowMessage(Jsobj.GetValue('userid').ToString);
//end;
end;
end;
Delphi XE5带了system.json单元,原生提供了json支持类。下面是解析json用法说明:
最简单的JSON大致像这样 {
"date":"周二(今天, 实时:12℃)",
"dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png",
"nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather":"多云",
"wind":"北风微风",
"temperature":"15 ~ 6℃"
} 对于这种格式比较简单的json,解析是非常容易的 StrJson := RESTResponse1.Content;
JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StrJson), ) as TJSONObject; JSONObject.getValue('date');
就可以得到date的值。如果像下面的这样结构比较复杂的json,就需要首先分析清楚这个json的格式才能获取成功。 {
"error":0,
"status":"success",
"date":"2014-03-04",
"results":
[{"currentCity":"成都",
"weather_data":[
{
"date":"周二(今天, 实时:12℃)",
"dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png",
"nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather":"多云",
"wind":"北风微风",
"temperature":"15 ~ 6℃"
},
{
"date":"周三",
"dayPictureUrl":"http://api.map.baidu.com/images/weather/day/yin.png",
"nightPictureUrl":"http://api.map.baidu.com/images/weather/night/xiaoyu.png",
"weather":"阴转小雨",
"wind":"北风微风",
"temperature":"14 ~ 7℃"
},
{
"date":"周四",
"dayPictureUrl":"http://api.map.baidu.com/images/weather/day/xiaoyu.png",
"nightPictureUrl":"http://api.map.baidu.com/images/weather/night/xiaoyu.png",
"weather":"小雨",
"wind":"北风微风",
"temperature":"12 ~ 7℃"
},
{
"date":"周五",
"dayPictureUrl":"http://api.map.baidu.com/images/weather/day/xiaoyu.png",
"nightPictureUrl":"http://api.map.baidu.com/images/weather/night/xiaoyu.png",
"weather":"小雨",
"wind":"南风微风",
"temperature":"9 ~ 6℃"
}
]
}
]} 这是一个嵌套结构,最外层是一个记录,包含"error", "status", "date", "results"四个字段,前三个都是简单的键值对,而“results”是一个数组,目前只有一个元素,即一条记录,这条记录的字段是"currentCity"和"weather_data",再进一步"weather_data"又是一个组数,它有4个元素或者记录,每条记录里包含 "date", "dayPictureUrl","nightPictureUrl", "weather","wind", "temperature"字段。
要想取出里面的"weather_data",利用目前的DBXJSON里的TJSONObject是不能直接取出来的,例如这样 StrJson := RESTResponse1.Content;
JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StrJson), )
as TJSONObject;
weather := JSONObject.GetValue('weather_data'); 需要一步一步的走,由于最外面是一个简单的json,可以先取出results,然后再取weather_data。
var JSONObject: TJSONObject;
LItem: TJSONValue;
LJPair: TJSONPair;
weather: TJSONArray;
StrJson: String;
result: String;
i: Integer;
begin
StrJson := 'xxxxxxx';//假定是上面那个json
JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StrJson), )
as TJSONObject;
JSONObject := (JSONObject.GetValue('results') as TJSONArray).Get()
as TJSONObject;
weather := JSONObject.GetValue('weather_data') as TJSONArray; for i := to weather.size - do //应该是4条记录
begin
LItem := (weather.Get(i) as TJSONObject).GetValue('weather'); //得到weather的值
result := result '|' LItem.Value;
end;
end 这段代码只是为了说明使用方法,没有做类型检查,最好在进行类型转换之前用is TJSONArray先判断是不是数组。 原文地址 补充,在原文中,作者没有提到,如何检查一个指定的串值是否存在,比如下面这行代码:
weather := JSONObject.GetValue('weather_data');
如果'weather_data'不存在,JSONObject.GetValue方法是要产生异常的,那么,该如何检查weath_data是否存在呢? 先声明一个
var
jsonvalue: Tjsonvalue;
然后,利用JSONObject.TryGetValue方法来检查。
if jsonObject.TryGetValue('weather_data', jsonvalue) then
...
如果weath_data存在,可以进一步通过jsonvalue.value取出其值。
注意,这个jsonvalue不用建立与释放。 --
网友发现上文中可能遇到的json串码问题,并给出了解决代码,Delphi <wbr>XE6 <wbr>原生解析jsonDelphi <wbr>XE6 <wbr>原生解析json!
procedure TForm1.Button2Click(Sender: TObject);
var
LJsonArr : TJSONArray;
LJsonValue : TJSONValue;
LItem : TJSONValue;
StrJson,S :string;
begin
StrJson := RESTresponse1.Content;
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StrJson),) as TJSONArray;
for LJsonValue in LJsonArr do
begin
for LItem in TJSONArray(LJsonValue) do
S :=Format('%s : %s',[TJSONPair(LItem).JsonString.Value, TJSONPair(LItem).JsonValue.Value]);
end;
end; 三、Demo三
{
功能:DelphiXE7中使用JSON
------------------------------------------------------------------------------
说明:
1,使用Delphi自己带的JSON(system.json)。
2,这仅仅是一个简单例子,以后还会增加演示功能。
------------------------------------------------------------------------------
注意:
1,JSON类创建后,里面所有元素不用管释放,JSON类自己管理,千万不要画蛇添足啊!!!!!!
------------------------------------------------------------------------------
作者:孙玉良 QQ:14667479 Email:sunylat@163.com 修改时间:2014/11/23 00:13
------------------------------------------------------------------------------
开发工具:Delphi XE7
测试手机:华为荣耀X1
}
unit Unit1; interface uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo; type
TForm1 = class(TForm)
Panel1: TPanel;
Memo1: TMemo;
Panel2: TPanel;
Button1: TButton;
Button2: TButton;
Memo2: TMemo;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations } // 重新设置button按钮
procedure ResetButton;
public
{ Public declarations }
end; var
Form1: TForm1; const
// 演示用的JSON
jsonString = '{"name":"张三", "other":["中国","程序员"]}'; implementation {$R *.fmx} uses
System.json; // Dephi自带的JSON单元 procedure TForm1.Button1Click(Sender: TObject);
var
JSONObject: TJSONObject; // JSON类
i: Integer; // 循环变量
temp: string; // 临时使用变量
jsonArray: TJSONArray; // JSON数组变量
begin if Trim(Memo1.Text) = '' then
begin
ShowMessage('要解析数据不能为空!');
end
else
begin
JSONObject := nil;
try
{ 从字符串生成JSON }
JSONObject := TJSONObject.ParseJSONValue(Trim(Memo1.Text)) as TJSONObject; if JSONObject.Count > then
begin { 1,遍历JSON数据 }
Memo2.Lines.Add('遍历JSON数据:' + ##); Memo2.Lines.Add('JSON数据数量:' + IntToStr(JSONObject.Count)); for i := to JSONObject.Count - do
begin if i = then
begin
temp := JSONObject.Get(i).ToString + ##;;
end
else
begin
temp := temp + JSONObject.Get(i).ToString + ##;
end; end; { output the JSON to console as String }
Memo2.Lines.Add(temp); Memo2.Lines.Add('------------------------------'); { 2,按元素解析JSON数据 }
Memo2.Lines.Add('按元素解析JSON数据:' + ##);
temp := 'name = ' + JSONObject.Values['name'].ToString + ##;
Memo2.Lines.Add(temp); // json数组
jsonArray := TJSONArray(JSONObject.GetValue('other'));;
if jsonArray.Count > then
begin // 得到JSON数组字符串
temp := 'other = ' + JSONObject.GetValue('other').ToString + ##; // 循环取得JSON数组中每个元素
for i := to jsonArray.Size - do
begin
temp := temp + IntToStr(i + ) + ' : ' + jsonArray.Items[i]
.Value + ##;
end; end; Memo2.Lines.Add(temp); end
else
begin
temp := '没有数据!';
Memo2.Lines.Add(temp);
end; finally
JSONObject.Free;
end;
end; end; // 清空显示数据
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Text := '';
Memo2.Text := '';
end; // 设置要解析的JSON数据
procedure TForm1.Button3Click(Sender: TObject);
begin
Memo1.Text := jsonString;
end; // 设置要解析的JSON数据
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Text := jsonString;
end; procedure TForm1.FormResize(Sender: TObject);
begin
// 重新设置button按钮
self.ResetButton;
end; // 重新设置button按钮
procedure TForm1.ResetButton;
var
buttonWidth: Integer;
begin
buttonWidth := self.Width div ; Button1.Width := buttonWidth;
Button2.Width := buttonWidth;
Button3.Width := buttonWidth;
end; end.
Xe7 System.Json解析数据格式的更多相关文章
- Json解析数据
Json数据解析(重点网址推荐:www.json.org code.google.com/ https://www.json.com/) 1:什么是Json? 2:Json数据格式的特点? 3 ...
- Android数据解析-JSON解析
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,基于JavaScript(Standard ECMA-262 3rd Edition - December ...
- json解析之jackson
对于json格式的数据解析现在越来越多了,之前介绍了两种:fastjson和net.sf.json解析. 今天又有一个jackson解析.不过相对于之前两种,这种感觉稍微笨拙些.呵呵,还是了解下吧: ...
- Java:JSON解析工具-org.json
一.简介 org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类,现在就各个类的使用解释如下. 二.准备 1.在使用org.json之前,我们应该先从该网 ...
- GeoJson的生成与解析,JSON解析,Java读写geojson,geotools读取shp文件,Geotools中Geometry对象与GeoJson的相互转换
GeoJson的生成与解析 一.wkt格式的geometry转成json格式 二.json格式转wkt格式 三.json格式的数据进行解析 四.Java读写geojson 五.geotools读取sh ...
- System.Json 使用注意
在xamarin中对json字符串进行解析,使用System.Json时出现怪问题: json-string = { "ret" : "OK" } 使用如下代码 ...
- Json解析工具的选择
前言 前段时间@寒江不钓同学针对国内Top500和Google Play Top200 Android应用做了全面的分析(具体分析报告见文末的参考资料),其中有涉及到对主流应用使用json框架Gson ...
- Android总结之json解析(FastJson Gson 对比)
前言: 最近为了统一项目中使用的框架,发现项目中用到了两种json解析框架,他们就是当今非常主流的json解析框架:google的Gson 和阿里巴巴的FastJson,为了废除其中一个所以来个性能和 ...
- Json解析工具Jackson(使用注解)
原文http://blog.csdn.net/nomousewch/article/details/8955796 接上一篇文章Json解析工具Jackson(简单应用),jackson在实际应用中给 ...
随机推荐
- 文字超长隐藏为...ie7不兼容的解决办法
把li里的a设置display:block; 代码如下: html: <ul> <li><span>2014-8-27</span><a href ...
- RPM安装MYSQL5.7
RPM安装MYSQL5.7 1:YUM安装依赖库 yum install perl libaio numactl 2:下载安装需要的RPM包 https://dev.mysql.com/get/Dow ...
- GPS获取坐标 显示Google map偏差计算
用手机获取GPS坐标 显示在手机地图偏差大约在100-200米左右,我把坐标放在 Maps.google.com 搜索坐标定位则相当精确. 可能是.....为了安全吧故意加的偏差 不过可以计算偏差使位 ...
- [UE4]控制台命令,生成机器人
在关卡蓝图中: 运行游戏的手,按“·”键(键盘第二行第一个键,数字1前面的一个键)呼出控制台输入界面,输入“ce 事件名称 参数值”,然后回车. 可以添加一个Trigger Box作为机器人的出生点
- Mybatis 系列8-结合源码解析select、resultMap的用法
[Mybatis 系列10-结合源码解析mybatis 执行流程] [Mybatis 系列9-强大的动态sql 语句] [Mybatis 系列8-结合源码解析select.resultMap的用法] ...
- jvm内存分区及各区线程问题
一.java内存模型图 二.直观分类图 三.各区简单描述 1.堆(heap):主要存放对象的实例也包括数组,是垃圾管理的主要作用区,是线程共享的 2.栈(stack):①虚拟机栈:描述的是 Java ...
- C# 将本地文件远程拷贝到其他电脑(转)
string newpath = System.IO.Path.GetFullPath(@"////10.144.26.252//d$//quyuan//图片" +"// ...
- Linux最大线程数限制及当前线程数查询
常用配置 echo > /proc/sys/kernel/pid_max a) 当前环境生效 ulimit -d unlimited ulimit -m unlimited ulimit -s ...
- 3-安装hive
1.解压.修改权限 tar -zvxf apache-hive-1.2.1-bin.tar.gz -C /opt/app/ sudo chown -R hadoop:hadoop /opt/app/a ...
- Linux设置Oracle环境变量
方法一:直接运行export命令定义变量,该变量只在当前的shell(BASH)或其子shell(BASH)下是有效的,shell关闭了,变量也就失效了,再打开新shell时就没有这个变量,需要使用的 ...