delphi怎么得到下面的json数据中的多个节点值。

披着虎皮的石头 2013-06-21 10:36:46
下面是UlkJson的第三方控件,来读取json的值。
如何取得childobject2":[{"obj2str1":"2one"},{"obj2str1":"2two"}]}中的
2one、2two的值?


// Sample 2: how to get child type and subobject fields
//
// Leonid Koninin, 02/03/2007
program sample2;
{$APPTYPE CONSOLE}
uses SysUtils, uLkJSON in 'uLkJSON.pas';
var JSon, XJSon :TlkJSONobject; JSonNode :TlkJSONString; JSonNodeList :TlkJSONlist; Str :String; i :Integer;
begin
Str := '{"string1":"one", "string2":"two", '
+'"childobject" : {"objstr1" :"Oone", "objstr2" :"Otwo"},'
+'"childobject2":[{"obj2str1":"2one"},{"obj2str1":"2two"}]}'; writeln(Str);

JSon := TlkJSON.ParseText(Str) as TlkJSONobject; // restore object (parse text)

if not assigned(JSon) then begin // how to obtain type of child
writeln('error: xs not assigned!'); readln; //exit;
end else begin //Field[] is 方式判断类型
if JSon.Field['childobject'] is TlkJSONString then writeln('type: xs is string!'); //string
if JSon.Field['childobject'] is TlkJSONlist then writeln('type: xs is list!'); //list 多个Json子节点
if JSon.Field['childobject'] is TlkJSONobject then writeln('type: xs is object!'); //Oject 单个json子节点

//以下类型,实际不常用
if JSon.Field['childobject'] is TlkJSONnumber then writeln('type: xs is number!'); //数字 value前后不加引号
if JSon.Field['childobject'] is TlkJSONboolean then writeln('type: xs is boolean!'); //boolean
if JSon.Field['childobject'] is TlkJSONnull then writeln('type: xs is null!'); //Null 改为空格值
end;

//Filed[].SelfType 方式判断类型
case JSon.Field['childobject'].SelfType of //the other way (0.93+)
jsString :writeln('other type: xs is string');
jsObject :writeln('other type: xs is object');
jsList :writeln('other type: xs is list');

jsNumber :writeln('other type: xs is number');
jsBoolean :writeln('other type: xs is boolean');
jsNull :writeln('other type: xs is null');
jsBase :writeln('other type: xs is base');
end;
writeln('self-type name: ', JSon.Field['childobject'].SelfTypeName);

XJSon :=JSon.Field['childobject'] as TlkJSONobject; //JSON中,有下级节点的,不像xml那样称为节点对象,仍称为JSOn对象

//Field[] as方式取值,完美
JSonNode :=XJSon.Field['objstr1'] as TlkJSONString; //we know what xs chilren are strings
writeln(JSonNode.value);

JSonNode :=XJSon.Field['objstr2'] as TlkJSONstring;
writeln(JSonNode.value);

//getstring,快速
writeln(XJSon.getString('objstr1')); //new v0.99 +syntax!
writeln(XJSon.getString('objstr2')); readln;

JSon.Free;
end.
...全文
345 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
http://www.codefans.net/soft/6097.shtml Delphi与Json数据交换格式的小例子

5,928

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧