c# - 无法将带有 [] 的索引应用于 JObject 类型的表达式
问题描述
这是我第一次来这里尝试解决问题,我已经学习 C# 4 周了,所以我不是你想象的专家,所以我从昨天开始一直在编码,我没有无法解决无论我做什么都会出现的错误“无法将 [] 索引应用于 JObject 类型的表达式”希望您能帮助我。
这是我的代码:
private static string GetTorrentUrl(string query)
{
WebClient client = new WebClient();
string json = client.DownloadString(new Uri("https://yts.mx/ajax/search?query=" + query));
Console.WriteLine(json);
JObject result = JObject.Parse(json);
if (result["status"].ToString == "ok")
{
JArray data = (JArray)result["data"];
Console.WriteLine(data[0]["title"].ToString());
}
return "something";
}
我只是尝试它并且它可以工作,但 Visual Studio 一直告诉我有一个错误。
解决方案
问题是您正在尝试获取属性,["status"]
即使您不知道(或编译器不知道)那是什么。
C# 是强类型的,因此编译器将在编译时检测并标记这些错误。
如果您查看文档,JObject
您会看到它实现了接口IEnumerable<KeyValuePair<String, JToken>>
::
公共类 JObject : JContainer, IDictionary<string, JToken>, ICollection<KeyValuePair<string, JToken>>, IEnumerable<KeyValuePair<string, JToken>>, IEnumerable, INotifyPropertyChanged, ICustomTypeDescriptor, INotifyPropertyChanging
阅读更多 -文档
这意味着您可以简单地使用循环来迭代列表:
foreach(var item in result)
{
if(item.Key == "status" && item.Value.ToString() == "ok")
// logic here
}
像这样使用 Linq 也应该可以这样做,但尚未测试代码:
private static string GetTorrentUrl(string query)
{
WebClient client = new WebClient();
string json = client.DownloadString(new Uri("https://yts.mx/ajax/search?query=" + query));
Console.WriteLine(json);
JObject result = JObject.Parse(json);
var status = result.Where(x => x.Key == "status").First().Value;
if(status == "ok")
{
JArray data = result.Where(x => x.Key == "data").First().Value;
Console.WriteLine(data[0]["title"].ToString());
}
return "something";
}
推荐阅读
- ruby-on-rails - Rails 应用程序不断加热 pg_type 和 pg_attribute 表如何减少此调用
- youtube-api - 尽管 Youtube API 返回错误,但已发布帖子
- selenium - Firefox 卡在使用 Selenium-Webdriver 进行登录操作
- java - 将计划的开始值和结束值建模为变量
- delphi - 操作属性下拉列表显示“您无法设置属性...”
- java - 将目录路径字符串从 Android 转发到 Lucene 库
- javascript - 通过加入两个数组来创建新数组
- javascript - 在 React/JS 中使用复杂路径进行动态导入
- ruby-on-rails - 不需要在每个 rswag 响应块中调用参数
- r - 如何使用 anova() 在虚拟交互中找到主效应的总体意义