从json响应中读取数据 [英] Read data from json response

查看:344
本文介绍了从json响应中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



例如:

  {
findCompletedItemsResponse
{
ack:[
成功
],
版本:[
1.13.0
] ,
timestamp:[
2016-06-02T16:07:36.736Z
],
searchResult:[
{
@count:2,
item:[
{
itemId:[
172168793372
],
标题:[
尼康D5000 12.3 MP数码单反相机(仅配备配件)
],
globalId:[
EBAY-US
],
primaryCategory:[
{
categoryId:[
31388
],
categoryName:[
数码相机
]
}
] ,
galleryURL:[
http:\ / \ / thumbs1.ebaystatic.com\ / m\ / mlRCNAriHPzowbSV9Q7ZFAg\ / 140.jpg
],
viewItemURL:[
http:\ / \ / www.ebay.com \ / itm\ / Nikon-D5000-12-3-MP-数码单反相机机身 - $

paymentMethod:[
PayPal
],
autoPay:[
false
],
邮政编码:[
02806
],
location:[
Barrington,RI,美国

country:[
US
],
shippingInfo:[
{
shippingServiceCost:[
{
@currencyId:USD,
__value __:0.0
}
],
shippingType:[
免费
],
shipToLocations:[
US
],
expeditedShipping:[
true
],
oneDayShippingAvailable:[
false
],
处理时间:[
2
]
}
] ,
sellStatus:[
{
currentPrice:[
{
@currencyId:USD,
__value __:178.5
}
],
convertedCurrentPrice:[
{
@currencyId:USD,
__value __:178.5
}
],
bidCount :[
13
],
sellState:[
EndedWithSales
]
}
],
listingInfo:[
{
bestOfferEnabled:[
false
],
buyItNowAvailable:[
false
],
startTime:[
$ 4


endTime:[
2016-04-25T18:45:54.000Z
],
listingType:[
拍卖
],
礼物:[

]
}

returnAccepted:[
false
],
条件:[
{
conditionId:[
3000
],
conditionDisplayName:[
使用
]
}
],
isMultiVariationListing :[
false
],
topRatedListing:[
false
]
},
{
itemId:[
172200026135
],
title:[
Nikon D5000 12.3 MP数码单反相机(仅配备配件)
],
globalId:[
EBAY-US
],
primaryCategory [
{
categoryId:[
31388
],
categoryName:[
数码相机
]
}
],
galleryURL:[
http:\ / \ / thumbs4.ebaystatic.com\ / m\ / mlRCNAriHPzowbSV9Q7ZFAg\ / 140 .jpg
],
viewItemURL:[
http:\ / \ / www.ebay.com\ / itm\ / Nikon-D5000-12-3 -MP-Di gital-SLR-Camera-Body-Only-Accessories-\ / 172200026135
],
paymentMethod:[
PayPal
],
自动付款:[
false
],
邮政编码:[
02806
],
位置:[
Barrington,RI,USA
],
country:[
US
],
shippingInfo:[
{
shippingServiceCost:[
{
@currencyId:USD,
__value __:0.0
}
]
shippingType:[
免费
],
shipToLocations:[
US
],
expeditedShipping:[
true
],
oneDayShippingAvailable:[
false
],
处理时间:[
2
]
}
],
sellStatus:[
{
currentPrice [
{
@currencyId:USD,
__value __:119.49
}
],
convertedCurrentPrice
{
@currencyId:USD,
__value __:119.49
}
],
bidCount:[
2
],
se l

listInfo:[
{
bestOfferEnabled:[
EndedWithSales
]
false
],
buyItNowAvailable:[
false
],
startTime:[
2016 -05-10T07:22:34.000Z
],
endTime:[
\"ODIM-16T19:22:25.000Z
],
listingType:[
拍卖
],
礼物:[

]
}
] ,
returnsAccepted:[
false
],
条件:[
{
conditionId:[
3000
],
conditionDisplayName:[
使用
]

],
isMultiVariationListing:[
false
],
topRatedListing:[
false
]
}
]
}
],
paginationOutput:[
{
pageNumber:[
1
],
entriesPerPage:[
100
],
totalPages:[
1
],
totalEntries:[
2
]
}
]
}
]
}

我只想提取th​​的价格e在ebay上列出的项目。我猜这是 currentPrice



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

解决方案

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



无论如何,您可以使用Delphi的内置函数,在 JSON框架中解析此JSON,例如:

 使用
System.JSON;

var
json:string;
obj:TJSONObject;
completedItems,sresults,items,status,price:TJSONArray;
I,J,K:整数;
currencyId,value:string;
begin
json:= ...; //< - 你的JSON字符串这里
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;
K:= 0 to items.Count-1 do
begin
status:=(items.Items [K] as TJSONObject).Values ['sellStatus'] as TJSONArray;
price:=((status.Items [0] as TJSONObject).Values ['currentPrice'])作为TJSONArray;
currencyId:= price.Values ['@ currencyId']。
value:= price.Values ['__ value __']。
//根据需要使用价格值...
end;
结束
finally
obj.Free;
结束
结束

或者:

 code>使用
System.JSON,System.JSON.Types;

var
json:string;
sreader:TStringReader;
jreader:TJsonTextReader;
inCurrentPrice:Boolean;
currencyId,value:string;
begin
json:= ...; //< - 你的JSON字符串这里
sreader:= TStringReader.Create(json);
try
jreader:= TJsonTextReader.Create(sreader);
try
inCurrentPrice:= False;
while jreader.Read do
begin
case jreader.TokenType
TJsonToken.PropertyName:begin
如果inCurrentPrice然后
begin
如果jreader .Value.AsString ='currencyId'然后开始
currencyId:= jreader.ReadAsString;
end
else if jreader.Value.AsString ='__value__'then begin
value:= jreader.ReadAsString;
结束
end
else if jreader.Value.AsString ='currentPrice'then
begin
currencyId:='';
value:='';
inCurrentPrice:= True;
结束
结束
TJsonToken.EndArray:begin
如果inCurrentPrice然后
begin
inCurrentPrice:= False;
//根据需要使用货币值...
end;
结束
结束
结束
finally
jreader.Free;
结束
finally
sreader.Free;
结束
结束


I am developing an application with Delphi 10 Seattle.

I am trying to read a value of an item from JSON.

For example :

{  
  "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"
          ]
        }
      ]
    }
  ]
}

I only want to extract the price of the listed item on ebay. Which is I guess the currentPrice.

How can I extract only the value of the price to a variable?

解决方案

This is horrible JSON. Whoever designed this data doesn't understand JSON at all. This JSON is grossly overusing 1-element arrays and string values. Most of the arrays do not belong at all, and JSON has other data types available (booleans, integers, etc).

In any case, you can use Delphi's built-in JSON framework to parse this JSON, eg:

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;

Alternatively:

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;

这篇关于从json响应中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆