从JSON字符串中获取特定值

时间:2018-12-11 16:10:40

标签: c# json api json.net

我有以下代码可以获取整个JSON字符串;但是,我只想得到cashprice

string url = "http://ondemand.websol.barchart.com/getGrainBids.json?apikey=12345&location=54943&commodityName=Corn%20(%232%20Yellow)&bidsPerCom=2";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
    using (StreamReader responseReader = new StreamReader(responseStream))
    {
        string json = responseReader.ReadToEnd();
        string data = JObject.Parse(json)["bids/price"].ToString();
        Label1.Text = data;
    }
}

我已注释掉的部分是我要工作的部分,但是每次尝试返回的值都只是一个空值。这是读取器运行时显示的JSON字符串:

{
  "status": {
    "code": 200,
    "message": "Success."
  },
  "results": [
    {
      "bids": [
        {
          "id": "19699878",
          "commodity": "CORN",
          "symbol": "ZCH19",
          "delivery_start": "2019-03-01 00:00:00",
          "delivery_end": "2019-03-31 23:59:59",
          "basis": "-35.00",
          "notes": null,
          "active": true,
          "sym_root": "ZC",
          "commodity_id": "119555",
          "customer_commodity_id": "5813",
          "commodity_display_name": "Corn (#2 Yellow)",
          "unitvalue": 1,
          "unitweight": 56,
          "deliveryMonth": "Mar19",
          "deliveryYear": "2019",
          "basismonth": "Mar 2019",
          "timestamp": 1544543949,
          "as_of": "09:59",
          "price": "3.48",
          "pricecwt": "6.205357",
          "basiscwt": -62.5,
          "pricetonne": "136.804545",
          "basistonne": -1377.8875,
          "change": "-0.015",
          "rawchange": -0.015,
          "pctchange": "-0.43",
          "cashprice": "3.48",
          "cashpricetonne": "136.804545",
          "delivery_sort": "2019-03-01 00:00:00",
          "delivery_start_raw": "2019-03-01 00:00:00",
          "delivery_end_raw": "2019-03-31 23:59:59",
          "basisSymbol": "ZCBH19-54943-5813.CM",
          "cashPriceSymbol": "ZCPH19-54943-5813.CM"
        },
        {
          "id": "14938531",
          "commodity": "CORN",
          "symbol": "ZCZ19",
          "delivery_start": "2019-12-01 00:00:00",
          "delivery_end": "2019-12-31 23:59:59",
          "basis": "-45.00",
          "notes": null,
          "active": true,
          "sym_root": "ZC",
          "commodity_id": "119555",
          "customer_commodity_id": "5813",
          "commodity_display_name": "Corn (#2 Yellow)",
          "unitvalue": 1,
          "unitweight": 56,
          "deliveryMonth": "Dec19",
          "deliveryYear": "2019",
          "basismonth": "Dec 2019",
          "timestamp": 1544543947,
          "as_of": "09:59",
          "price": "3.56",
          "pricecwt": "6.361607",
          "basiscwt": -80.3571428571,
          "pricetonne": "140.249263",
          "basistonne": -1771.56964286,
          "change": "-0.01",
          "rawchange": -0.01,
          "pctchange": "-0.28",
          "cashprice": "3.56",
          "cashpricetonne": "140.249263",
          "delivery_sort": "2019-12-01 00:00:00",
          "delivery_start_raw": "2019-12-01 00:00:00",
          "delivery_end_raw": "2019-12-31 23:59:59",
          "basisSymbol": "ZCBZ19-54943-5813.CM",
          "cashPriceSymbol": "ZCPZ19-54943-5813.CM"
        }
      ],
      "distance": null,
      "company": "Ag Partners",
      "locationId": 54943,
      "location": "Brown/Sab/Rulo/WC",
      "facility_type": "Country Elevator",
      "address": "2750 Acorn Rd",
      "city": "Sabetha",
      "state": "KS",
      "lng": -95.786193,
      "lat": 39.9061537,
      "phone": "785-284-2185",
      "url": "www.agpartnerscoop.com",
      "zip": "66534",
      "county": "Nemaha County",
      "basisTimestamp": "2018-12-11T09:02:48-06:00"
    }
  ]
}

任何建议如何正确显示3.48?我确定这是我所缺少的小东西。

4 个答案:

答案 0 :(得分:2)

JSON中有多个出价。如果您只想获得第一个,可以使用SelectToken并提供如下路径:

JObject jo = JObject.Parse(json);
string cashPrice = (string)jo.SelectToken("results[0].bids[0].cashprice");
Label1.Text = cashPrice;

提琴:https://dotnetfiddle.net/rUklUq

如果要获取所有出价的价格,可以使用SelectTokens并使用通配符,如下所示:

JObject jo = JObject.Parse(json);

List<string> allPrices = jo.SelectTokens("results[0].bids[*].cashprice")
                           .Values<string>()
                           .ToList();

提琴:https://dotnetfiddle.net/lGbJEe

答案 1 :(得分:1)

您需要将Json字符串转换为Json对象并获取结果数组。

JSONObject jsonObject = new JSONObject(jsonString);

拥有Json对象后,您需要获取results[]并循环遍历以获取Bids[],然后在其中可以获取cashprice

答案 2 :(得分:1)

对于这样的事情,我们喜欢使用JsonPaths。如果您想尝试这种方式,请参考以下参考资料。 http://jsonpath.com/https://goessner.net/articles/JsonPath/index.html#e2

  var data = JObject.Parse(json).SelectTokens("$.results[*].bids[*].price");
  var result = data;

答案 3 :(得分:0)

布莱恩(Brian)有一个完美的答案:

JObject jo = JObject.Parse(json);
string cashPrice = (string)jo.SelectToken("results[0].bids[0].cashprice");
Label1.Text = cashPrice;