我正在使用WinForms(C#)查找Google和Bing中的排名和关键字排名。为此我正在使用Newtonsoft.Json.Net2.0.dll
。当我正在运行该过程时,它显示错误:
无法访问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;
}
}
答案 0 :(得分:2)
这很可能是由于NewtonSoft库试图将对象绑定到不存在的属性。在行
SearchType searchResult = JsonConvert.DeserializeObject<SearchType>(result.ToString());
由于结果包含SearchType中不存在的属性,反序列化可能会失败。