我正在尝试从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
{
"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引用异常)。您可以在尝试根据需要访问值之前添加空检查。