来自RESTful查询的简单Json - 无法反序列化

时间:2013-05-10 19:46:17

标签: c# json web-services rest

我是REST / JSON新手,我正在查询Feedzilla API的新闻文章,关键字 syria

http://api.feedzilla.com/v1/categories/26/articles/search.json?q=syria

    public FZResult Search(string query)
    {
        //_client.BaseUrl = string.Format("http://api.feedzilla.com/v1/categories/26/articles/search.json}", StackExchangeSite);
        _client.BaseUrl = string.Format("http://api.feedzilla.com/v1/categories/26/articles/search.json");

        RestRequest request = new RestRequest();

        //Required
        request.AddParameter("q", "syria");

        //Output
        RestResponse response = (RestResponse)_client.Execute(request);

        IDeserializer deserializer;
        deserializer = new JsonDeserializer();

        //The format that Wikipedia uses
        deserializer.DateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";

        FZResult results = deserializer.Deserialize<FZResult>(response);

        return results;
    }

FZResult课程如下所示:

 public class FZResult
    {
        [DeserializeAs(Name = "items")]
        public List<ResultItem> Items { get; set; }

    }

我的ResultItem课程如下:

  public class ResultItem
    {
        [DeserializeAs(Name = "title")]
        public string title { get; set; }

        [DeserializeAs(Name = "url")]
        public string url { get; set; }

    }

但是,上述FZResult方法的Search()会返回null。我已经检查了JSON是否正确形成并且能够解析它 - 我确信它与类定义和...有关。 DeserializeAs ...

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您的问题似乎是FZResult类。如果查看从服务返回的json,则根元素是一个名为articles的数组。你的课程有[DeserializeAs(Name = "items")],这可能会混淆反序列化引擎,因为Name应该是articles

尝试更改这些值并检查新结果。

遗憾的是,我还没有尝试过RestSharp。以下代码使用Newtonsoft.JSON和常规HttpWebRequest来获取结果。我已经确认它正在工作。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;

namespace FeedZilla
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.feedzilla.com/v1/categories/26/articles/search.json?q=syria");

            using (var responseStream = request.GetResponse().GetResponseStream())
            {
                using (var reader = new StreamReader(responseStream))
                {
                    var fzResult = Newtonsoft.Json.JsonConvert.DeserializeObject<FZResult>(reader.ReadToEnd());

                    fzResult.Articles.ForEach(a => Console.WriteLine("{0} {1}", a.Title, a.Url));
                }
            }
        }

        [DataContract]
        public class FZResult
        {
            [DataMember(Name = "articles")]
            public List<Article> Articles { get; set; }
        }

        public class Article
        {
            [DataMember(Name = "title")]
            public string Title { get; set; }

            [DataMember(Name = "url")]
            public string Url { get; set; }
        }
    }
}