2017-11-25 158 views
1

我試圖挽救兩個變量進行JSON請求,但我只是想拿到第一個工作,這是我的要求:.NET API無法找到數據我想

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); 

這將返回該錯誤:

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]; 

這將返回:

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

這是我試過的JSON分離它自己作爲它剛剛作爲一個長線的網址:

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

我在做什麼錯?謝謝。

+0

您的「數據」數組中只有一個元素,並且您要求[3]中的第三個元素。您嘗試的另一件事是請求Trustflow數組的第一個元素,但Trustflow不是數組。在第二次嘗試時放下[0]? –

+0

數組基於0索引。因此,您將以「someArray [0]' – Shyju

+0

@MarcTalbot的形式訪問第一個項目,它會返回相同的錯誤'帶有無效鍵值的訪問JArray值:」TrustFlow「。 Int32數組索引預期。'對不起,我打算說,當我說它返回Int32它返回它在上一級,我會編輯 – liamcook

回答

2

您的Data屬性是一個大小爲1的數組。數組基於0索引。所以,你要訪問的第一個項目爲someArray[0]和第二項爲someArray[1]

讀取存儲數據數組中的第一個項目的TrustFlow屬性內的int值,你可以這樣做

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

這應該適用於您在問題中提供的JSON數據。請記住,該代碼預計數據將在該結構中。例如,如果您的Data陣列沒有任何項目,或者您的Results沒有Data屬性,則代碼將崩潰(可能是空引用異常)。您可以在嘗試根據需要訪問該值之前自行添加空檢查。

+1

作品夢想!謝謝!還沒有任何陣列的經驗,但真的清除了我,以及使它的工作:)謝謝! – liamcook

相關問題