Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access child value on Newtonsoft.Json.Linq.JValue

I'm working on WinForms (C#) to find the ranks and keyword positions in Google and Bing. For this I'm using Newtonsoft.Json.Net2.0.dll. While I'm running the process it shows the error:

Cannot access child value on Newtonsoft.Json.Linq.JValue.

How can I solve this problem?

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;
    }
}
like image 346
Victor Avatar asked Nov 04 '22 22:11

Victor


1 Answers

This is most likely due to the NewtonSoft library trying to bind an object to non-existant properties. In the line

SearchType searchResult = JsonConvert.DeserializeObject<SearchType>(result.ToString());

the deserialization may be failing due to result containing properties that don't exist in SearchType.

like image 177
Mo. Avatar answered Nov 09 '22 05:11

Mo.