【问题标题】:C# Retrieving a specific piece of information from JSON string by using Newtonsoft.jsonC# 使用 Newtonsoft.json 从 JSON 字符串中检索特定信息
【发布时间】:2021-04-28 08:57:55
【问题描述】:

我检索到的 JSON 字符串:

{
  "trackItemResponse" : {
    "hdr" : {
      "messageType" : "TRACKITEM",
      "messageDateTime" : "2021-04-28T16:32:05+08:00",
      "messageVersion" : "1.0",
      "messageLanguage" : "en"
    },
    "bd" : {
      "shipmentItems" : [ {
        "masterShipmentID" : null,
        "shipmentID" : "MYCGUMY8202104SIN00005",
        "trackingID" : "5021049762931421",
        "orderNumber" : null,
        "handoverID" : null,
        "shippingService" : {
          "productCode" : "PDO",
          "productName" : "Parcel Domestic"
        },
        "consigneeAddress" : {
          "country" : "MY"
        },
        "weight" : "804",
        "dimensionalWeight" : "640",
        "weightUnit" : "G",
        "events" : [ {
          "status" : "77093",
          "description" : "Successfully delivered",
          "dateTime" : "2021-04-06 13:47:56",
          "timezone" : "LT",
          "address" : {
            "city" : "Skudai",
            "postCode" : "81300",
            "state" : "JOHOR",
            "country" : "MY"
          }
        }, {
          "status" : "77090",
          "description" : "Out for Delivery",
          "dateTime" : "2021-04-06 10:51:55",
          "timezone" : "LT",
          "address" : {
            "city" : "Skudai",
            "postCode" : "81300",
            "state" : "JOHOR",
            "country" : "MY"
          }
        }, {
          "status" : "77184",
          "description" : "Processed at delivery facility",
          "dateTime" : "2021-04-06 07:56:07",
          "timezone" : "LT",
          "address" : {
            "city" : "Skudai",
            "postCode" : "81300",
            "state" : "Johor",
            "country" : "MY"
          }
        }, {
          "status" : "77178",
          "description" : "Arrived at facility",
          "dateTime" : "2021-04-06 07:30:26",
          "timezone" : "LT",
          "address" : {
            "city" : "Skudai",
            "postCode" : "81300",
            "state" : "Johor",
            "country" : "MY"
          }
        }, {
          "status" : "77169",
          "description" : "Departed from facility",
          "dateTime" : "2021-04-06 05:22:02",
          "timezone" : "LT",
          "address" : {
            "city" : "Kuala Lumpur Hub",
            "postCode" : "47100",
            "state" : "Kuala Lumpur",
            "country" : "MY"
          }
        }, {
          "status" : "77027",
          "description" : "Sorted to delivery facility",
          "dateTime" : "2021-04-05 21:00:05",
          "timezone" : "LT",
          "address" : {
            "city" : "Kuala Lumpur Hub",
            "postCode" : "47100",
            "state" : "Kuala Lumpur",
            "country" : "MY"
          }
        }, {
          "status" : "77015",
          "description" : "Processed at facility",
          "dateTime" : "2021-04-05 20:59:04",
          "timezone" : "LT",
          "address" : {
            "city" : "Kuala Lumpur Hub",
            "postCode" : "47100",
            "state" : "Kuala Lumpur",
            "country" : "MY"
          }
        }, {
          "status" : "71005",
          "description" : "DATA SUBMITTED",
          "dateTime" : "2021-04-02 15:44:40",
          "timezone" : "Malaysia",
          "address" : {
            "city" : "SEPANG, SELANGOR",
            "postCode" : "43900",
            "state" : "SEL",
            "country" : "MY"
          }
        } ]
      } ],
      "responseStatus" : {
        "code" : "200",
        "message" : "SUCCESS",
        "messageDetails" : [ {
          "messageDetail" : "1 tracking reference(s) tracked, 1 tracking reference(s) found."
        } ]
      }
    }
  }
}

我想要的输出:

5021049762931421 //trackingID

我尝试过的方法_1:

HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     string result = streamReader.ReadToEnd();
     Console.WriteLine(result);
     dynamic data = JObject.Parse(result);
     Console.WriteLine(data.trackItemResponse.bd.shipmentItems.trackingID);
}

输出:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''Newtonsoft.Json.Linq.JArray' does not contain a definition for 'trackingID''

我尝试过的方法_2:

HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var trckID = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"].Select(x => (string)x["trackingID"]).ToList();
     Console.WriteLine("Below is json data");
     Console.WriteLine(trckID);
     Console.WriteLine("Until here la");
}

输出_2:

Below is json data
System.Collections.Generic.List`1[System.String]
Until here la

我尝试过的方法_3:

HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     string jsonData = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"]["trackingID"].ToString();
     Console.WriteLine("Below is json data");
     Console.WriteLine(jsonData);
     Console.WriteLine("Until here la");
}

输出_3:

System.ArgumentException: 'Accessed JArray values with invalid key value: "trackingID". Int32 array index expected.'

还有其他可行的方法吗?谢谢。

我推荐过的帖子

Convert string to int C#

C# cast from string to int/int32

Make newtonsoft.json convert default to int32 rather than int64

C# extract json array with newtonsoft.json

感谢您的热心帮助!

【问题讨论】:

  • 您能否决定是否需要shipmentIDtrackingID,并酌情更新问题。
  • shipmentItems 是一个数组,这是您问题的根源。也许你只需要shipmentItems[0],如果总是有一个项目的话。
  • @Jamiec 我想要trackingID,很抱歉造成混乱

标签: c# json json.net


【解决方案1】:

您正在寻找

var result = JObject.Parse(result)["trackItemResponse"]["bd"]["shipmentItems"][0]["trackingID"].ToString();

但请记住,shipmentItems 是一个列表,因此可能包含多个项目。
此代码仅检查该列表中的第一个。

【讨论】:

    【解决方案2】:

    SelectToken 就是你要找的东西:

    var semiParsedJson = JObject.Parse(json);
    var trackingId = semiParsedJson
        .SelectToken("trackItemResponse.bd.shipmentItems[0].trackingID");
    

    请记住,此解决方案假定shipmentItems 集合中的第一个对象包含所需的信息。

    如果不存在,则 trackingId 将是 null


    如果您在 shipmentItems 中有多个对象,并且您对所有 trackingId 值感兴趣,那么您必须使用 SelectTokens

    var semiParsedJson = JObject.Parse(json);
    var trackingIds = semiParsedJson
        .SelectTokens("trackItemResponse.bd.shipmentItems[*].trackingID");
    

    请注意,索引器运算符现在收到一个* 通配符。

    【讨论】:

      【解决方案3】:

      根据您的代码,您就快到了。 由于对象“data.trackItemResponse.bd.shipmentItems”是一个数组,所以需要在选择索引后访问“trackingID”。

      你的代码应该是:

      HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
      using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
      {
           string result = streamReader.ReadToEnd();
           Console.WriteLine(result);
           dynamic data = JObject.Parse(result);
           
           //Test this 
           var trackingID = data.trackItemResponse.bd.shipmentItems[0].trackingID;
           Console.WriteLine(data.trackItemResponse.bd.shipmentItems[0].trackingID);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多