15

私は 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
}

私が達成したかったのは、各アイテム (つまり財布) を解析し、1 つのサブアイテム (製造元) と共にリストビューのキャプションとして追加することでした。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;

どんな提案でも大歓迎です。Delphi で JSON のインとアウトを取得しようとしてかなりの時間を無駄にしました。

ありがとう、スフィンクス

4

3 に答える 3

30

このサンプルを試す

{$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.

これは戻ります

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
于 2012-05-30T03:36:35.467 に答える
6

このサイトでは、タイプTJSONValueについて詳しく説明しています。データがオブジェクトの場合、タイプTJSONObjectは になるため、その API をチェックして処理方法を確認してください。

ペアを反復処理するために最初に必要なことだと思います(GetEnumeratorキー名がわからない場合は使用し、それ以外の場合はオーバーロードを使用しますGet-数値の代わりに文字列を渡します)。ペアごとに、キーは単純な文字列 ( type TJSONString) になり、値は any になりますTJSONValue。葉に到達するまで繰り返します。

例:

products   := jPair.Get('products');
purse      := products.GetJsonValue().Get('Purse');
purseManuf := purse.GetJsonValue().Get('manufacturer');
...

または、製品が何であるかわからない場合:

products   := jPair.Get('products');
for prodPair in products.GetEnumerator() do
begin
    prodName := prodPair.GetJsonString();
    prodObj  := prodPair.GetJsonValue();
    ...
于 2012-05-30T02:28:55.113 に答える
1

このブログ投稿は、JSON を変換する非常にモダンでシンプルな方法を示しています。

uses REST.JSON; // Also new System.JSON
procedure TForm1.Button1Click(Sender: TObject);

var
  Foo: TFoo;

begin
  Foo := TFoo.Create;

  try
    Foo.Foo := 'Hello World';
    Foo.Fee := 42;
    Memo1.Lines.Text := TJson.ObjectToJsonString(Foo);
  finally
    Foo.Free;
  end;

  Foo := TJson.JsonToObject<TFoo>(Memo1.Lines.Text);

  try
    Foo.Fee := 100;
    Memo1.Lines.Add(TJson.ObjectToJsonString(Foo));
  finally
    Foo.Free;
  end;
end;
于 2016-04-18T16:57:59.407 に答える