Csharp/C#教程:使用无效键值访问JArray值:“fields”。 预期数组位置索引分享


使用无效键值访问JArray值:“fields”。 预期数组位置索引

我正在使用监护人API来尝试和检索故事但仍然收到exception。 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":"https://www.theguardian.com/sustainable-business/sustainable-finance-where-next-open-thread", "apiUrl":"https://content.guardianapis.com/sustainable-business/sustainable-finance-where-next-open-thread", "fields":{ "body":"Csharp/C#教程:使用无效键值访问JArray值:“fields”。  预期数组位置索引分享..." } }] } } 

我尝试过包括这个在内的所有事情:

 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值:“fields”。 预期数组位置索引。

at Newtonsoft.Json.Linq.JArray.get_Item(Object key)

如果你更换

 // 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"]; 

这应该适用于你的例子。 请注意在您提供的示例中得到的方括号,表示应在访问代码中考虑的数组。

上述就是C#学习教程:使用无效键值访问JArray值:“fields”。 预期数组位置索引分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1027834.html

(0)
上一篇 2022年1月10日
下一篇 2022年1月10日

精彩推荐