首页 > 解决方案 > 无法将带有 [] 的索引应用于 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 一直告诉我有一个错误

标签: c#

解决方案


问题是您正在尝试获取属性,["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";
}

推荐阅读