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

Bog*_*atu 15 delphi json nested delphi-xe2

我是JSON的新手,我手上有这个项目,需要我解析一个JSON并在ListView中显示它的一些内容.问题是我现在阅读的文档处理的是包含JSON数组的JSON对象,而我的案例涉及处理嵌套对象.简而言之,这里是摘要:我正在使用带有DBXJSON的Delphi XE2.我将一些值发布到服务器,并使用看起来像这样的JSON对象进行回复:

    {
    "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
}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是将每个项目(即Purse)解析并添加为listview中的标题,以及一个子项目(制造商).我创建了一个以JSON字符串作为参数的过程,创建了JSON对象,但我不知道如何进一步解析嵌套对象.

procedure TForm1.ParseString(const AString: string);
var
  json          : TJSONObject;
  jPair         : TJSONPair;
  jValue        : TJSONValue;
  jcValue       : TJSONValue;
  l,i           : Integer;
begin
    json    := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(AString),0) as TJSONObject;
  try
    //get the pair to evaluate in this case the index is 1
    jPair   := json.Get(1); 
        {further process the nested objects and adding them to the listview}
  finally
     json.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

任何建议都将受到高度赞赏.失去了相当一段时间试图在Delphi中获取JSON的来龙去脉.

谢谢,sphynx

RRU*_*RUZ 28

试试这个样本

{$APPTYPE CONSOLE}

{$R *.res}

uses
  DBXJSON,
  System.SysUtils;


Const
StrJson=
'{'+
'    "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
        begin
           if TJSONPair(LItem).JsonValue is TJSONFalse then
            Writeln(Format('  %s : %s',[TJSONPair(LItem).JsonString.Value, 'false']))
           else
           if 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.
Run Code Online (Sandbox Code Playgroud)

这将返回

Product Name Men's Sneakers
  instock : false
  size : 423
  manufacturer : Adidas
  lastcheck : 20120529
Product Name Purse
  instock : true
  size : not applicable
  manufacturer : Prada
  lastcheck : 20120528
Product Name Men's Hood
  instock : false
  size : M
  manufacturer : Generic
  lastcheck : 20120529
Run Code Online (Sandbox Code Playgroud)


mgi*_*nbr 6

该站点TJSONValue更详细地描述了该类型.如果您的数据是对象,则它将具有类型TJSONObject,因此请检查其API以了解如何继续.

我相信你需要它首先迭代它的对(GetEnumerator如果你不知道键名,请使用,否则只使用重载Get- 传递字符串而不是数字).对于每对,键将是一个简单的字符串(类型TJSONString),值可以是任意值TJSONValue.重复,直到你到达叶子.

例:

products   := jPair.Get('products');
purse      := products.GetJsonValue().Get('Purse');
purseManuf := purse.GetJsonValue().Get('manufacturer');
...
Run Code Online (Sandbox Code Playgroud)

或者,如果您不知道产品是什么:

products   := jPair.Get('products');
for prodPair in products.GetEnumerator() do
begin
    prodName := prodPair.GetJsonString();
    prodObj  := prodPair.GetJsonValue();
    ...
Run Code Online (Sandbox Code Playgroud)