.NET API 找不到我想要的数据

.NET API Can't Find Data I Want

我正在尝试从 json 请求中保存两个变量,但我只是想让第一个变量正常工作,这是我的请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.majestic.com/api/json?app_api_key=KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majestic.com&datasource=fresh");
  {
     WebResponse response = request.GetResponse();
     using (Stream responseStream = response.GetResponseStream())
       {
          StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
          JObject jObject = JObject.Parse(reader.ReadToEnd());
          JToken Trusty = jObject["DataTables"]["Results"]["Data"][2];
          var newdomain = new Identifier { domain = model.domain, contact = model.contact, contactname = model.contactname, price = model.price, type = model.type, TrustFlow = Int32.Parse(Trusty.ToString()), CitationFlow = 65, RI = model.RI, MJTopicsID = model.MJTopicsID, UserTableID = model.UserTableID };
          ViewBag.newdomain = newdomain;
          db.Identifiers.Add(newdomain);

这个returns这个错误:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'

我也试过了

Token Trusty = jObject["DataTables"]["Results"]["Data"]["TrustFlow"][0];

这个returns:

'Accessed JArray values with invalid key value: "TrustFlow". Int32 array index expected.'

这是 json 我自己尝试将它分开,因为 url 它只是一长串:

{
"Code":"OK","ErrorMessage":"","FullError":"","FirstBackLinkDate":"2017-08-17","IndexBuildDate":"2017-11-20 10:51:56","IndexType":1,"MostRecentBackLinkDate":"2017-11-18","QueriedRootDomains":0,"QueriedSubDomains":0,"QueriedURLs":1,"QueriedURLsMayExist":0,"ServerBuild":"2017-10-25 14:33:44","ServerName":"QUACKYO","ServerVersion":"1.0.6507.24412","UniqueIndexID":"20171120105156-FRESH",
"DataTables":{
    "Results":{
         "Headers":{
"MaxTopicsRootDomain":30,"MaxTopicsSubDomain":20,"MaxTopicsURL":10,"TopicsCount":3
    },
         "Data":[{
"RefDomainTypeProtocolHTTPS":"228","CitationFlow":42,"TrustFlow":29,"TrustMetric":29,"TopicalTrustFlow_Topic_0":"Health/Animal","TopicalTrustFlow_Value_0":26,"TopicalTrustFlow_Topic_1":"Business","TopicalTrustFlow_Value_1":25,"TopicalTrustFlow_Topic_2":"Computers/Internet/Domain Names","TopicalTrustFlow_Value_2":24
    }
]}}}

我做错了什么?谢谢。

您的 Data 属性 是一个大小为 1 的数组。数组是基于 0 索引的。因此,您将以 someArray[0] 访问第一项,以 someArray[1] 访问第二项,依此类推

要读取存储在数据数组第一项的 TrustFlow 属性 中的 int 值,您可以这样做

int trustFlow = jObject["DataTables"]["Results"]["Data"][0]["TrustFlow"].Value<int>();

这应该适用于您在问题中提供的 JSON 数据。请记住,此代码期望数据位于该结构中。例如,如果您的 Data 数组没有任何项,或者您的 Results 没有 Data 属性,代码将崩溃(可能会出现空引用异常).您可以在尝试根据需要访问该值之前自行添加 null 检查。