【发布时间】:2017-11-25 23:46:58
【问题描述】:
我正在尝试从 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);
这会返回这个错误:
System.ArgumentOutOfRangeException: '索引超出范围。必须是非负数且小于集合的大小。'
我也试过了
Token Trusty = jObject["DataTables"]["Results"]["Data"]["TrustFlow"][0];
返回:
'使用无效键值访问的 JArray 值:“TrustFlow”。应为 Int32 数组索引。'
这是我自己尝试将它分开的 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
}
]}}}
我做错了什么?谢谢。
【问题讨论】:
-
您的“数据”数组中只有一个元素,而您使用 [2] 请求第三个元素。您尝试的另一件事是要求 Trustflow 数组的第一个元素,但 Trustflow 不是数组。在第二次尝试时删除 [0]?
-
数组基于 0 索引。因此,您将以
someArray[0]的身份访问第一项 -
@MarcTalbot 它返回相同的错误“使用无效键值访问的 JArray 值:“TrustFlow”。需要 Int32 数组索引。对不起,我的意思是当我说它返回 Int32 时它会返回上一个级别,我会编辑
-
@Shyju 我知道 data 会是一个数组,所以它会是 Data[2] 吗?
-
@Shyju 啊我看到它在数据部分打开了一个数组,其中 [] 怎么写?
标签: c# asp.net asp.net-mvc asp.net-mvc-4