【问题标题】:Accessed JArray values with invalid key value: "fields". Array position index expected使用无效键值访问的 JArray 值:“字段”。预期数组位置索引
【发布时间】:2014-03-16 05:23:38
【问题描述】:

我正在使用 Guardian API 来尝试检索故事,但一直收到异常。 json 字符串包含以下 json,但是我无法使用 LINQ 访问正文。

这里是:

{
    "response":{
    "status":"ok",
    "userTier":"approved",
    "total":1,
    "startIndex":1,
    "pageSize":10,
    "currentPage":1,
    "pages":1,
    "orderBy":"newest",
    "results":[{
      "id":"sustainable-business/sustainable-finance-where-next-open-thread",
      "sectionId":"sustainable-business",
      "sectionName":"Guardian Sustainable Business",
      "webPublicationDate":"2014-02-13T13:27:00Z",
      "webTitle":"Where next for sustainable finance? - open thread",
      "webUrl":"http://www.theguardian.com/sustainable-business/sustainable-finance-where-next-open-thread",
      "apiUrl":"http://content.guardianapis.com/sustainable-business/sustainable-finance-where-next-open-thread",
      "fields":{
        "body":"<img src=\"http://hits.theguardian.com/b/ss/guardiangu-api/1/H.20.3/98867?ns=guardian&amp;pageName=Where+next+for+sustainable+finance%3F+-+open+thread+Article+2043222&amp;ch=Guardian+Sustainable+Business&amp;c2=461773&amp;c4=MIC%3A+Finance+%28GSB%29%2CMIC%3A+Guardian+Sustainable+Business%2CPRO%3A+Sustainability+%28Guardian+Professional%29&amp;c3=theguardian.com&amp;c6=Laura+Paddison&amp;c7=14-Feb-13&amp;c8=2043222&amp;c9=Article\" width=\"1\" height=\"1\" />..."
      }
     }]
     }
}

我已经尝试了所有的东西,包括这个:

string story = (string)ja["response"]["results"]["fields"]["body"];

更新:

public partial class Story : PhoneApplicationPage
{
    string url;
    string jsonData;

    // Http used so the json can be retrived via the get async methods
    HttpClient webClient = new HttpClient();

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (NavigationContext.QueryString.ContainsKey("key"))
        {
            string encodedValue = NavigationContext.QueryString["key"];
            url = Uri.UnescapeDataString(encodedValue);
            textBox.Text = url;
            guardianPanorama();
        }
    }
    private async void guardianPanorama()
    {
        try
        {
            HttpResponseMessage Result = await webClient.GetAsync(url);

            // This takes the http response content and is turned into a string
            jsonData = await Result.Content.ReadAsStringAsync();
           
            JObject ja = JObject.Parse(jsonData);

            // This takes the current bitcoin price and formats it so there is the      correct amount of decimal places
            string story = (string)ja["response"]["results"]["fields"]["body"];

            // It then gets added to the textbox
            textBox.Text = story;
        }
        catch (Exception errors)
        {
            MessageBox.Show("There has been a error with the Guardian API");
            Console.WriteLine("An error occured:" + errors);
        }
    }
}

例外:

System.ArgumentException:使用无效键值访问的 JArray 值:“字段”。应为数组位置索引。

在 Newtonsoft.Json.Linq.JArray.get_Item(对象键)

【问题讨论】:

  • 你能发布你如何检索'ja' JSON对象的代码吗?
  • 以及如果您发布异常。谢谢
  • 已添加,感谢您的帮助
  • 或许应该是string story = (string)ja["response"]["results"][0]["fields"]["body"];results 是一个数组...
  • 你是明星伴侣!如何为您的帐户 +1?

标签: c# json linq windows-phone json.net


【解决方案1】:

如果你替换

// This takes the current bitcoin price and formats it so there is the correct amount of decimal places
string story = (string)ja["response"]["results"]["fields"]["body"];

// This takes the current bitcoin price and formats it so there is the correct amount of decimal places
string story = (string)ja["response"]["results"][0]["fields"]["body"];

这应该适用于您的示例。请注意您提供的示例中结果后面的方括号,它表示应该在您的访问代码中考虑的数组。

【讨论】:

  • 如果第一个响应是数组形式而第二个响应不是数组形式怎么办。有什么方法可以知道响应是否为数组形式?
  • @NickKing 我认为您可以简单地检查JToken 的类型并检查它是否是 JArray。
  • 我同意,但我有一个复杂的 json,我想知道我的 json 最里面的 json 对象的类型。例如,在这个问题的 json 中,我想检查“结果”对象(在“响应”中)是否是列表。
  • @NickKing 所以你必须检查最里面的对象类型。不确定你的问题是什么。也许,您想写一个新问题来全面描述您的问题。
  • 我不确定是否仍然可以使用 JToken 检查最里面的对象类型。但是我做了一个快速测试,我可以检查最里面的对象是否是一个数组。谢谢!!
猜你喜欢
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
相关资源
最近更新 更多