栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Delphi XE2中解析嵌套的JSON对象?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Delphi XE2中解析嵌套的JSON对象?

试试这个样本

{$APPTYPE CONSOLE}{$R *.res}uses  DBXJSON,  System.SysUtils;ConstStrJson='{'+'    "products": {'+'        "Men''s Sneakers": {'+' "instock": false,'+' "size": "423",'+' "manufacturer": "Adidas",'+' "lastcheck": "20120529"'+'        },'+'        "Purse": {'+' "instock": true,'+' "size": "not applicable",'+' "manufacturer": "Prada",'+' "lastcheck": "20120528"'+'        },'+'        "Men''s Hood": {'+' "instock": false,'+' "size": "M",'+' "manufacturer": "Generic",'+' "lastcheck": "20120529"'+'        }'+'    },'+'    "total": 41,'+'    "available": 30'+'}';procedure ParseJson;var  LJsonObj  : TJSONObject;  LJPair    : TJSONPair;  LProducts : TJSONValue;  LProduct  : TJSONValue;  LItem     : TJSONValue;  LIndex    : Integer;  LSize     : Integer;begin    LJsonObj    := TJSONObject.ParseJSonValue(TEncoding.ASCII.GetBytes(StrJson),0) as TJSONObject;  try     LProducts:=LJsonObj.Get('products').JsonValue;     LSize:=TJSonArray(LProducts).Size;     for LIndex:=0 to LSize-1 do     begin      LProduct := TJSonArray(LProducts).Get(LIndex);      LJPair   := TJSonPair(LProduct);      Writeln(Format('Product Name %s',[LJPair.JsonString.Value]));        for LItem in TJSonArray(LJPair.JsonValue) do        beginif TJSonPair(LItem).JsonValue is TJSonFalse then Writeln(Format('  %s : %s',[TJSonPair(LItem).JsonString.Value, 'false']))elseif TJSonPair(LItem).JsonValue is TJSonTrue then Writeln(Format('  %s : %s',[TJSonPair(LItem).JsonString.Value, 'true']))else Writeln(Format('  %s : %s',[TJSonPair(LItem).JsonString.Value, TJSonPair(LItem).JsonValue.Value]));        end;     end;  finally     LJsonObj.Free;  end;end;begin  try    ParseJson;  except    on E: Exception do      Writeln(E.ClassName, ': ', E.Message);  end;  Readln;end.

这将返回

Product Name Men's Sneakers  instock : false  size : 423  manufacturer : Adidas  lastcheck : 20120529Product Name Purse  instock : true  size : not applicable  manufacturer : Prada  lastcheck : 20120528Product Name Men's Hood  instock : false  size : M  manufacturer : Generic  lastcheck : 20120529


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404170.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号