我正在使用 WinForms (C#) 查找 Google 和 Bing 中的排名和关键字位置。为此,我使用 Newtonsoft.Json.Net2.0.dll
。当我运行该过程时,它显示错误:
Cannot access child value on Newtonsoft.Json.Linq.JValue.
我该如何解决这个问题?
public class GoogleSearch
{
public int Search(string siteUrl, string searchExpression, ref string stage)
{
int position = 100;
const string urlTemplate = @"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
var resultsList = new List<SearchType>();
int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
foreach (var offset in offsets)
{
var searchUrl = new Uri(string.Format(urlTemplate, searchExpression, offset));
string page = new WebClient().DownloadString(searchUrl);
JObject googleSearch = JObject.Parse(page);
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();//here i got the error ...
IList<SearchType> searchResults = new List<SearchType>();
foreach (JToken result in results)
{
SearchType searchResult = JsonConvert.DeserializeObject<SearchType>(result.ToString());
resultsList.Add(searchResult);
}
}
int i = 0;
foreach (SearchType s in resultsList)
{
i = i + 1;
if (s.Url.Contains(siteUrl))
{
position = i;
return position;
}
}
return position;
}
}
最佳答案
这很可能是由于 NewtonSoft 库试图将对象绑定(bind)到不存在的属性。在行中
SearchType searchResult = JsonConvert.DeserializeObject<SearchType>(result.ToString());
由于结果包含 SearchType 中不存在的属性,反序列化可能会失败。
关于c# - 无法访问 Newtonsoft.Json.Linq.JValue 上的子值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865309/