微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 无法访问Newtonsoft.Json.Linq.JValue上的子值

我正在使用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库试图将对象绑定到不存在的属性.在线

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

由于结果包含SearchType中不存在的属性,反序列化可能会失败.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐