从json响应中读取数据

时间:2016-06-02 14:54:02

标签: json delphi

我正在使用Delphi 10 Seattle开发应用程序。

我正在尝试从JSON中读取项目的值。

例如:

{  
  "findCompletedItemsResponse":[  
    {  
      "ack":[  
        "Success"
      ],
      "version":[  
        "1.13.0"
      ],
      "timestamp":[  
        "2016-06-02T16:07:36.736Z"
      ],
      "searchResult":[  
        {  
          "@count":"2",
          "item":[  
            {  
              "itemId":[  
                "172168793372"
              ],
              "title":[  
                "Nikon D5000 12.3 MP Digital SLR Camera (Body Only with Accessories)"
              ],
              "globalId":[  
                "EBAY-US"
              ],
              "primaryCategory":[  
                {  
                  "categoryId":[  
                    "31388"
                  ],
                  "categoryName":[  
                    "Digital Cameras"
                  ]
                }
              ],
              "galleryURL":[  
                "http:\/\/thumbs1.ebaystatic.com\/m\/mlRCNAriHPzowbSV9Q7ZFAg\/140.jpg"
              ],
              "viewItemURL":[  
                "http:\/\/www.ebay.com\/itm\/Nikon-D5000-12-3-MP-Digital-SLR-Camera-Body-Only-Accessories-\/172168793372"
              ],
              "paymentMethod":[  
                "PayPal"
              ],
              "autoPay":[  
                "false"
              ],
              "postalCode":[  
                "02806"
              ],
              "location":[  
                "Barrington,RI,USA"
              ],
              "country":[  
                "US"
              ],
              "shippingInfo":[  
                {  
                  "shippingServiceCost":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"0.0"
                    }
                  ],
                  "shippingType":[  
                    "Free"
                  ],
                  "shipToLocations":[  
                    "US"
                  ],
                  "expeditedShipping":[  
                    "true"
                  ],
                  "oneDayShippingAvailable":[  
                    "false"
                  ],
                  "handlingTime":[  
                    "2"
                  ]
                }
              ],
              "sellingStatus":[  
                {  
                  "currentPrice":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"178.5"
                    }
                  ],
                  "convertedCurrentPrice":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"178.5"
                    }
                  ],
                  "bidCount":[  
                    "13"
                  ],
                  "sellingState":[  
                    "EndedWithSales"
                  ]
                }
              ],
              "listingInfo":[  
                {  
                  "bestOfferEnabled":[  
                    "false"
                  ],
                  "buyItNowAvailable":[  
                    "false"
                  ],
                  "startTime":[  
                    "2016-04-18T18:45:54.000Z"
                  ],
                  "endTime":[  
                    "2016-04-25T18:45:54.000Z"
                  ],
                  "listingType":[  
                    "Auction"
                  ],
                  "gift":[  
                    "false"
                  ]
                }
              ],
              "returnsAccepted":[  
                "false"
              ],
              "condition":[  
                {  
                  "conditionId":[  
                    "3000"
                  ],
                  "conditionDisplayName":[  
                    "Used"
                  ]
                }
              ],
              "isMultiVariationListing":[  
                "false"
              ],
              "topRatedListing":[  
                "false"
              ]
            },
            {  
              "itemId":[  
                "172200026135"
              ],
              "title":[  
                "Nikon D5000 12.3 MP Digital SLR Camera (Body Only with Accessories)"
              ],
              "globalId":[  
                "EBAY-US"
              ],
              "primaryCategory":[  
                {  
                  "categoryId":[  
                    "31388"
                  ],
                  "categoryName":[  
                    "Digital Cameras"
                  ]
                }
              ],
              "galleryURL":[  
                "http:\/\/thumbs4.ebaystatic.com\/m\/mlRCNAriHPzowbSV9Q7ZFAg\/140.jpg"
              ],
              "viewItemURL":[  
                "http:\/\/www.ebay.com\/itm\/Nikon-D5000-12-3-MP-Digital-SLR-Camera-Body-Only-Accessories-\/172200026135"
              ],
              "paymentMethod":[  
                "PayPal"
              ],
              "autoPay":[  
                "false"
              ],
              "postalCode":[  
                "02806"
              ],
              "location":[  
                "Barrington,RI,USA"
              ],
              "country":[  
                "US"
              ],
              "shippingInfo":[  
                {  
                  "shippingServiceCost":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"0.0"
                    }
                  ],
                  "shippingType":[  
                    "Free"
                  ],
                  "shipToLocations":[  
                    "US"
                  ],
                  "expeditedShipping":[  
                    "true"
                  ],
                  "oneDayShippingAvailable":[  
                    "false"
                  ],
                  "handlingTime":[  
                    "2"
                  ]
                }
              ],
              "sellingStatus":[  
                {  
                  "currentPrice":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"119.49"
                    }
                  ],
                  "convertedCurrentPrice":[  
                    {  
                      "@currencyId":"USD",
                      "__value__":"119.49"
                    }
                  ],
                  "bidCount":[  
                    "2"
                  ],
                  "sellingState":[  
                    "EndedWithSales"
                  ]
                }
              ],
              "listingInfo":[  
                {  
                  "bestOfferEnabled":[  
                    "false"
                  ],
                  "buyItNowAvailable":[  
                    "false"
                  ],
                  "startTime":[  
                    "2016-05-10T07:22:34.000Z"
                  ],
                  "endTime":[  
                    "2016-05-16T19:22:25.000Z"
                  ],
                  "listingType":[  
                    "Auction"
                  ],
                  "gift":[  
                    "false"
                  ]
                }
              ],
              "returnsAccepted":[  
                "false"
              ],
              "condition":[  
                {  
                  "conditionId":[  
                    "3000"
                  ],
                  "conditionDisplayName":[  
                    "Used"
                  ]
                }
              ],
              "isMultiVariationListing":[  
                "false"
              ],
              "topRatedListing":[  
                "false"
              ]
            }
          ]
        }
      ],
      "paginationOutput":[  
        {  
          "pageNumber":[  
            "1"
          ],
          "entriesPerPage":[  
            "100"
          ],
          "totalPages":[  
            "1"
          ],
          "totalEntries":[  
            "2"
          ]
        }
      ]
    }
  ]
}

我只想在易趣上提取所列物品的价格。我猜是currentPrice

如何仅将价格的值提取到变量?

2 个答案:

答案 0 :(得分:4)

这是可怕的JSON。设计这些数据的人根本不了解JSON。这个JSON严重过度使用1元素数组和字符串值。大多数数组根本不属于,JSON还有其他可用的数据类型(布尔值,整数等)。

无论如何,你可以使用Delphi的内置JSON framework来解析这个JSON,例如:

uses
  System.JSON;

var
  json: string;
  obj: TJSONObject;
  completedItems, sresults, items, status, price: TJSONArray;
  I, J, K: Integer;
  currencyId, value: string;
begin
  json := ...; // <-- your JSON string here
  obj := TJSONObject.ParseJSONValue(json, 0) as TJSONObject;
  try
    completedItems := obj.Values['findCompletedItemsResponse'] as TJSONArray;
    for I := 0 to completedItems.Count-1 do
    begin
      sresults := (completedItems.Items[I] as TJSONObject).Values['searchResult'] as TJSONArray;
      for J := 0 to sresults.Count-1 do
      begin
        items := (sresults.Items[J] as TJSONObject).Values['item'] as TJSONArray;
        for K := 0 to items.Count-1 do
        begin
          status := (items.Items[K] as TJSONObject).Values['sellingStatus'] as TJSONArray;
          price := ((status.Items[0] as TJSONObject).Values['currentPrice']) as TJSONArray;
          currencyId := price.Values['@currencyId'].Value;
          value := price.Values['__value__'].Value;
          // use price values as needed...
        end;
      end;
    finally
      obj.Free;
    end;
  end;

可替换地:

uses
  System.JSON, System.JSON.Types;

var
  json: string;
  sreader: TStringReader;
  jreader: TJsonTextReader;
  inCurrentPrice: Boolean;
  currencyId, value: string;
begin
  json := ...; // <-- your JSON string here
  sreader := TStringReader.Create(json);
  try
    jreader := TJsonTextReader.Create(sreader);
    try
      inCurrentPrice := False;
      while jreader.Read do
      begin
        case jreader.TokenType of
          TJsonToken.PropertyName: begin
            if inCurrentPrice then
            begin
              if jreader.Value.AsString = 'currencyId' then begin
                currencyId := jreader.ReadAsString;
              end
              else if jreader.Value.AsString = '__value__' then begin
                value := jreader.ReadAsString;
              end;
            end
            else if jreader.Value.AsString = 'currentPrice' then
            begin
              currencyId := '';
              value := '';
              inCurrentPrice := True;
            end;
          end;
          TJsonToken.EndArray: begin
            if inCurrentPrice then
            begin
              inCurrentPrice := False;
              // use currency values as needed...
            end;
          end;
        end;
      end;
    finally
      jreader.Free;
    end;
  finally
    sreader.Free;
  end;
end;

答案 1 :(得分:2)

您可以使用此类工具为此JSON生成信封。

http://www.pgeorgiev.com/?p=1832

代码如下所示:

unit Test1;

//  *************************************************
//    Generated By: JsonToDelphiClass - 0.65
//    Project link: https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass
//    Generated On: 2016-06-02 17:46:09
//  *************************************************
//    Created By  : Petar Georgiev - 2014
//    WebSite     : http://pgeorgiev.com
//  *************************************************

interface

uses Generics.Collections, Rest.Json;

type

TConditionClass = class
private
  FConditionDisplayName: TArray<String>;
  FConditionId: TArray<String>;
public
  property conditionDisplayName: TArray<String> read FConditionDisplayName write FConditionDisplayName;
  property conditionId: TArray<String> read FConditionId write FConditionId;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TConditionClass;
end;

TListingInfoClass = class
private
  FBestOfferEnabled: TArray<String>;
  FBuyItNowAvailable: TArray<String>;
  FEndTime: TArray<String>;
  FGift: TArray<String>;
  FListingType: TArray<String>;
  FStartTime: TArray<String>;
public
  property bestOfferEnabled: TArray<String> read FBestOfferEnabled write FBestOfferEnabled;
  property buyItNowAvailable: TArray<String> read FBuyItNowAvailable write FBuyItNowAvailable;
  property endTime: TArray<String> read FEndTime write FEndTime;
  property gift: TArray<String> read FGift write FGift;
  property listingType: TArray<String> read FListingType write FListingType;
  property startTime: TArray<String> read FStartTime write FStartTime;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TListingInfoClass;
end;

TConvertedCurrentPriceClass = class
private
  FAcurrencyId: String;
  F__value__: String;
public
  property AcurrencyId: String read FAcurrencyId write FAcurrencyId;
  property __value__: String read F__value__ write F__value__;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TConvertedCurrentPriceClass;
end;

TCurrentPriceClass = class
private
  FAcurrencyId: String;
  F__value__: String;
public
  property AcurrencyId: String read FAcurrencyId write FAcurrencyId;
  property __value__: String read F__value__ write F__value__;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TCurrentPriceClass;
end;

TSellingStatusClass = class
private
  FBidCount: TArray<String>;
  FConvertedCurrentPrice: TArray<TConvertedCurrentPriceClass>;
  FCurrentPrice: TArray<TCurrentPriceClass>;
  FSellingState: TArray<String>;
public
  property bidCount: TArray<String> read FBidCount write FBidCount;
  property convertedCurrentPrice: TArray<TConvertedCurrentPriceClass> read FConvertedCurrentPrice write FConvertedCurrentPrice;
  property currentPrice: TArray<TCurrentPriceClass> read FCurrentPrice write FCurrentPrice;
  property sellingState: TArray<String> read FSellingState write FSellingState;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TSellingStatusClass;
end;

TShippingInfoClass = class
private
  FExpeditedShipping: TArray<String>;
  FHandlingTime: TArray<String>;
  FOneDayShippingAvailable: TArray<String>;
  FShipToLocations: TArray<String>;
  FShippingType: TArray<String>;
public
  property expeditedShipping: TArray<String> read FExpeditedShipping write FExpeditedShipping;
  property handlingTime: TArray<String> read FHandlingTime write FHandlingTime;
  property oneDayShippingAvailable: TArray<String> read FOneDayShippingAvailable write FOneDayShippingAvailable;
  property shipToLocations: TArray<String> read FShipToLocations write FShipToLocations;
  property shippingType: TArray<String> read FShippingType write FShippingType;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TShippingInfoClass;
end;

TProductIdClass = class
private
  FAtype: String;
  F__value__: String;
public
  property Atype: String read FAtype write FAtype;
  property __value__: String read F__value__ write F__value__;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TProductIdClass;
end;

TPrimaryCategoryClass = class
private
  FCategoryId: TArray<String>;
  FCategoryName: TArray<String>;
public
  property categoryId: TArray<String> read FCategoryId write FCategoryId;
  property categoryName: TArray<String> read FCategoryName write FCategoryName;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TPrimaryCategoryClass;
end;

TItemClass = class
private
  FAutoPay: TArray<String>;
  FCondition: TArray<TConditionClass>;
  FCountry: TArray<String>;
  FGalleryURL: TArray<String>;
  FGlobalId: TArray<String>;
  FIsMultiVariationListing: TArray<String>;
  FItemId: TArray<String>;
  FListingInfo: TArray<TListingInfoClass>;
  FLocation: TArray<String>;
  FPaymentMethod: TArray<String>;
  FPostalCode: TArray<String>;
  FPrimaryCategory: TArray<TPrimaryCategoryClass>;
  FProductId: TArray<TProductIdClass>;
  FReturnsAccepted: TArray<String>;
  FSellingStatus: TArray<TSellingStatusClass>;
  FShippingInfo: TArray<TShippingInfoClass>;
  FTitle: TArray<String>;
  FTopRatedListing: TArray<String>;
  FViewItemURL: TArray<String>;
public
  property autoPay: TArray<String> read FAutoPay write FAutoPay;
  property condition: TArray<TConditionClass> read FCondition write FCondition;
  property country: TArray<String> read FCountry write FCountry;
  property galleryURL: TArray<String> read FGalleryURL write FGalleryURL;
  property globalId: TArray<String> read FGlobalId write FGlobalId;
  property isMultiVariationListing: TArray<String> read FIsMultiVariationListing write FIsMultiVariationListing;
  property itemId: TArray<String> read FItemId write FItemId;
  property listingInfo: TArray<TListingInfoClass> read FListingInfo write FListingInfo;
  property location: TArray<String> read FLocation write FLocation;
  property paymentMethod: TArray<String> read FPaymentMethod write FPaymentMethod;
  property postalCode: TArray<String> read FPostalCode write FPostalCode;
  property primaryCategory: TArray<TPrimaryCategoryClass> read FPrimaryCategory write FPrimaryCategory;
  property productId: TArray<TProductIdClass> read FProductId write FProductId;
  property returnsAccepted: TArray<String> read FReturnsAccepted write FReturnsAccepted;
  property sellingStatus: TArray<TSellingStatusClass> read FSellingStatus write FSellingStatus;
  property shippingInfo: TArray<TShippingInfoClass> read FShippingInfo write FShippingInfo;
  property title: TArray<String> read FTitle write FTitle;
  property topRatedListing: TArray<String> read FTopRatedListing write FTopRatedListing;
  property viewItemURL: TArray<String> read FViewItemURL write FViewItemURL;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TItemClass;
end;

TSearchResultClass = class
private
  FAcount: String;
  FItem: TArray<TItemClass>;
public
  property Acount: String read FAcount write FAcount;
  property item: TArray<TItemClass> read FItem write FItem;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TSearchResultClass;
end;

TFindCompletedItemsResponseClass = class
private
  FAck: TArray<String>;
  FSearchResult: TArray<TSearchResultClass>;
  FTimestamp: TArray<String>;
  FVersion: TArray<String>;
public
  property ack: TArray<String> read FAck write FAck;
  property searchResult: TArray<TSearchResultClass> read FSearchResult write FSearchResult;
  property timestamp: TArray<String> read FTimestamp write FTimestamp;
  property version: TArray<String> read FVersion write FVersion;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TFindCompletedItemsResponseClass;
end;

TRootClass = class
private
  FFindCompletedItemsResponse: TArray<TFindCompletedItemsResponseClass>;
public
  property findCompletedItemsResponse: TArray<TFindCompletedItemsResponseClass> read FFindCompletedItemsResponse write FFindCompletedItemsResponse;
  destructor Destroy; override;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TRootClass;
end;

implementation

{TConditionClass}


function TConditionClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TConditionClass.FromJsonString(AJsonString: string): TConditionClass;
begin
  result := TJson.JsonToObject<TConditionClass>(AJsonString)
end;

{TListingInfoClass}


function TListingInfoClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TListingInfoClass.FromJsonString(AJsonString: string): TListingInfoClass;
begin
  result := TJson.JsonToObject<TListingInfoClass>(AJsonString)
end;

{TConvertedCurrentPriceClass}


function TConvertedCurrentPriceClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TConvertedCurrentPriceClass.FromJsonString(AJsonString: string): TConvertedCurrentPriceClass;
begin
  result := TJson.JsonToObject<TConvertedCurrentPriceClass>(AJsonString)
end;

{TCurrentPriceClass}


function TCurrentPriceClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TCurrentPriceClass.FromJsonString(AJsonString: string): TCurrentPriceClass;
begin
  result := TJson.JsonToObject<TCurrentPriceClass>(AJsonString)
end;

{TSellingStatusClass}

destructor TSellingStatusClass.Destroy;
var
  LcurrentPriceItem: TCurrentPriceClass;
  LconvertedCurrentPriceItem: TConvertedCurrentPriceClass;
begin

 for LcurrentPriceItem in FCurrentPrice do
   LcurrentPriceItem.free;
 for LconvertedCurrentPriceItem in FConvertedCurrentPrice do
   LconvertedCurrentPriceItem.free;

  inherited;
end;

function TSellingStatusClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TSellingStatusClass.FromJsonString(AJsonString: string): TSellingStatusClass;
begin
  result := TJson.JsonToObject<TSellingStatusClass>(AJsonString)
end;

{TShippingInfoClass}


function TShippingInfoClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TShippingInfoClass.FromJsonString(AJsonString: string): TShippingInfoClass;
begin
  result := TJson.JsonToObject<TShippingInfoClass>(AJsonString)
end;

{TProductIdClass}


function TProductIdClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TProductIdClass.FromJsonString(AJsonString: string): TProductIdClass;
begin
  result := TJson.JsonToObject<TProductIdClass>(AJsonString)
end;

{TPrimaryCategoryClass}


function TPrimaryCategoryClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TPrimaryCategoryClass.FromJsonString(AJsonString: string): TPrimaryCategoryClass;
begin
  result := TJson.JsonToObject<TPrimaryCategoryClass>(AJsonString)
end;

{TItemClass}

destructor TItemClass.Destroy;
var
  LprimaryCategoryItem: TPrimaryCategoryClass;
  LproductIdItem: TProductIdClass;
  LshippingInfoItem: TShippingInfoClass;
  LsellingStatusItem: TSellingStatusClass;
  LlistingInfoItem: TListingInfoClass;
  LconditionItem: TConditionClass;
begin

 for LprimaryCategoryItem in FPrimaryCategory do
   LprimaryCategoryItem.free;
 for LproductIdItem in FProductId do
   LproductIdItem.free;
 for LshippingInfoItem in FShippingInfo do
   LshippingInfoItem.free;
 for LsellingStatusItem in FSellingStatus do
   LsellingStatusItem.free;
 for LlistingInfoItem in FListingInfo do
   LlistingInfoItem.free;
 for LconditionItem in FCondition do
   LconditionItem.free;

  inherited;
end;

function TItemClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TItemClass.FromJsonString(AJsonString: string): TItemClass;
begin
  result := TJson.JsonToObject<TItemClass>(AJsonString)
end;

{TSearchResultClass}

destructor TSearchResultClass.Destroy;
var
  LitemItem: TItemClass;
begin

 for LitemItem in FItem do
   LitemItem.free;

  inherited;
end;

function TSearchResultClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TSearchResultClass.FromJsonString(AJsonString: string): TSearchResultClass;
begin
  result := TJson.JsonToObject<TSearchResultClass>(AJsonString)
end;

{TFindCompletedItemsResponseClass}

destructor TFindCompletedItemsResponseClass.Destroy;
var
  LsearchResultItem: TSearchResultClass;
begin

 for LsearchResultItem in FSearchResult do
   LsearchResultItem.free;

  inherited;
end;

function TFindCompletedItemsResponseClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TFindCompletedItemsResponseClass.FromJsonString(AJsonString: string): TFindCompletedItemsResponseClass;
begin
  result := TJson.JsonToObject<TFindCompletedItemsResponseClass>(AJsonString)
end;

{TRootClass}

destructor TRootClass.Destroy;
var
  LfindCompletedItemsResponseItem: TFindCompletedItemsResponseClass;
begin

 for LfindCompletedItemsResponseItem in FFindCompletedItemsResponse do
   LfindCompletedItemsResponseItem.free;

  inherited;
end;

function TRootClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TRootClass.FromJsonString(AJsonString: string): TRootClass;
begin
  result := TJson.JsonToObject<TRootClass>(AJsonString)
end;

end.

获得它后,您可以获得与此类似的代码。

procedure TForm1.Button1Click(Sender: TObject);
var
  cr:TRootClass;
  rc:TFindCompletedItemsResponseClass;
  sr:TSearchResultClass;
  it:TItemClass;
  ss:TSellingStatusClass;
  cp:TCurrentPriceClass;
  str:string;
begin
  cr := TRootClass.FromJsonString(Memo1.Lines.Text);
  rc := cr.findCompletedItemsResponse[0];
  sr := rc.searchResult[0];
  it := sr.item[0];
  ss := it.sellingStatus[0];
  cp := ss.currentPrice[0];
  // current price
  Str := cp.__value__;      <<=======
end;

问候。

PD:请花更长的时间来提出更好的问题以获得更好的答案。