将包含对象列表的JSON响应反序列化为C#类

时间:2011-12-07 14:27:40

标签: c# json serialization json.net

我正在使用NewsBlur API返回Feed列表。响应JSON的类型为:

{
    "authenticated": true,
    "user": "sathyabhat",
    "feeds": {},
    "flat_folders": { },
    result: "ok"
}

其中feeds:的类型为

    "feeds": {
        "96705": {
            "feed_address": "http://www.linuxhaxor.net/",
            "updated": "8492 hours",
            "favicon_text_color": null,
            "subs": 35,
            "feed_link": "http://www.linuxhaxor.net/",
            "favicon_fetching": true,
            "nt": 0,
            "updated_seconds_ago": 30573336,
            "num_subscribers": 35,
            "feed_title": "LinuxHaxor.net",
            "favicon_fade": null,
            "exception_type": "feed",
            "exception_code": 503,
            "favicon_color": null,
            "active": true,
            "ng": 0,
            "feed_opens": 0,
            "id": 96705,
            "ps": 0,
            "has_exception": true
        },
        "768840": {
            "feed_address": "http://feeds.feedburner.com/PathikShahDotCom",
            "updated": "3 hours",
            "favicon_text_color": "black",
            "subs": 1,
            "feed_link": "http://www.pathikshah.com/blog",
            "favicon_fetching": false,
            "nt": 0,
            "updated_seconds_ago": 13043,
            "num_subscribers": 1,
            "feed_title": "Pathik Shah",
            "favicon_fade": "769456",
            "favicon_color": "b2d092",
            "active": true,
            "ng": 0,
            "feed_opens": 0,
            "id": 768840,
            "ps": 0
        },
        "768842": {
            "feed_address": "http://feeds.preshit.net/preshit/blog",
            "updated": "3 hours",
            "favicon_text_color": null,
            "subs": 1,
            "feed_link": "http://preshit.net",
            "favicon_fetching": false,
            "nt": 3,
            "updated_seconds_ago": 13536,
            "num_subscribers": 1,
            "feed_title": "Preshit Deorukhkar",
            "favicon_fade": null,
            "favicon_color": null,
            "active": true,
            "ng": 0,
            "feed_opens": 1,
            "id": 768842,
            "ps": 0
        },
        "768843": {
            "feed_address": "http://quizwith.net/feed/",
            "updated": "3 hours",
            "favicon_text_color": "white",
            "subs": 1,
            "feed_link": "http://quizwith.net",
            "favicon_fetching": false,
            "nt": 0,
            "updated_seconds_ago": 11617,
            "num_subscribers": 1,
            "feed_title": "quizwith.net",
            "favicon_fade": "c22900",
            "favicon_color": "fe6501",
            "active": true,
            "ng": 0,
            "feed_opens": 0,
            "id": 768843,
            "ps": 0
        }

[...等等......]

    }

基本上,它是一个feed对象列表。现在,我正在尝试使用JSON.net将其反序列化为C#对象,但我的类成员填充了空值。

我的课程以我得到的答案为蓝本:

 public class FeedResponse
    {
   public string authenticated { get; set; }
   public string user { get; set; }
   public List<feed> feeds { get; set; }
   public string flat_folders { get; set; }
   public string result { get; set; }
}

public class feed
{
    public string feed_address { get; set; }
    public string updated { get; set; }
    public string favicon_text_color { get; set; }
    public int subs { get; set; }
    public string feed_link { get; set; }
    public bool favicon_fetching { get; set; }
    public string nt { get; set; }
    public string updated_seconds_ago { get; set; }
    public int num_subscribers { get; set; }
    public string feed_title { get; set; }
    public string favicon_fade { get; set; }
    public string exception_type { get; set; }
    public string exception_code { get; set; }
    public string favicon_color { get; set; }
    public bool active { get; set; }
    public string ng { get; set; }
    public int feed_opens { get; set; }
    public int id { get; set; }
    public bool has_exception { get; set; }

}

这是尝试反序列化的行(使用RestSharp):

 return Execute<FeedResponse>(request);

显然,在尝试解析JSON以获取Feed响应时出现问题。

关于我做错了什么的指示?

3 个答案:

答案 0 :(得分:5)

Feed是Dictionary<int,Feed>而不是List<Feed>(theres是Keys)。

编辑:更多细节,json中的对象列表看起来像这样:

[{ name: 'elem1'},
{ name: 'elem2'},
{ name: 'elem3'}]

edit2:完整的样本工作:

 using System; 
 using System.Collections.Generic; 
 using System.Linq;
 using System.Web.Script.Serialization;

 namespace JSON {
     class Program
     {
         static void Main(string[] args)
         {
             var json = @"{
     ""authenticated"": true,
     ""user"": ""sathyabhat"",
     ""feeds"": {
         ""96705"": {
             ""feed_address"": ""http://www.linuxhaxor.net/"",
             ""updated"": ""8492 hours"",
             ""favicon_text_color"": null,
             ""subs"": 35,
             ""feed_link"": ""http://www.linuxhaxor.net/"",
             ""favicon_fetching"": true,
             ""nt"": 0,
             ""updated_seconds_ago"": 30573336,
             ""num_subscribers"": 35,
             ""feed_title"": ""LinuxHaxor.net"",
             ""favicon_fade"": null,
             ""exception_type"": ""feed"",
             ""exception_code"": 503,
             ""favicon_color"": null,
             ""active"": true,
             ""ng"": 0,
             ""feed_opens"": 0,
             ""id"": 96705,
             ""ps"": 0,
             ""has_exception"": true
         },
         ""768840"": {
             ""feed_address"": ""http://feeds.feedburner.com/PathikShahDotCom"",
             ""updated"": ""3 hours"",
             ""favicon_text_color"": ""black"",
             ""subs"": 1,
             ""feed_link"": ""http://www.pathikshah.com/blog"",
             ""favicon_fetching"": false,
             ""nt"": 0,
             ""updated_seconds_ago"": 13043,
             ""num_subscribers"": 1,
             ""feed_title"": ""Pathik Shah"",
             ""favicon_fade"": ""769456"",
             ""favicon_color"": ""b2d092"",
             ""active"": true,
             ""ng"": 0,
             ""feed_opens"": 0,
             ""id"": 768840,
             ""ps"": 0
         },
         ""768842"": {
             ""feed_address"": ""http://feeds.preshit.net/preshit/blog"",
             ""updated"": ""3 hours"",
             ""favicon_text_color"": null,
             ""subs"": 1,
             ""feed_link"": ""http://preshit.net"",
             ""favicon_fetching"": false,
             ""nt"": 3,
             ""updated_seconds_ago"": 13536,
             ""num_subscribers"": 1,
             ""feed_title"": ""Preshit Deorukhkar"",
             ""favicon_fade"": null,
             ""favicon_color"": null,
             ""active"": true,
             ""ng"": 0,
             ""feed_opens"": 1,
             ""id"": 768842,
             ""ps"": 0
         },
         ""768843"": {
             ""feed_address"": ""http://quizwith.net/feed/"",
             ""updated"": ""3 hours"",
             ""favicon_text_color"": ""white"",
             ""subs"": 1,
             ""feed_link"": ""http://quizwith.net"",
             ""favicon_fetching"": false,
             ""nt"": 0,
             ""updated_seconds_ago"": 11617,
             ""num_subscribers"": 1,
             ""feed_title"": ""quizwith.net"",
             ""favicon_fade"": ""c22900"",
             ""favicon_color"": ""fe6501"",
             ""active"": true,
             ""ng"": 0,
             ""feed_opens"": 0,
             ""id"": 768843,
             ""ps"": 0
         }
     },
     ""flat_folders"": { },
     result: ""ok"" }";

             var jsonSerializer = new JavaScriptSerializer();
             var response = jsonSerializer.Deserialize<FeedResponse(json);
             Console.Write(jsonSerializer.Serialize(response));
             Console.ReadKey();
         }
     }

     public class FeedResponse
     {
         public bool authenticated { get; set; }
         public string user { get; set; }
         public Dictionary<string,feed> feeds { get; set; }
         public object flat_folders { get; set; }
         public string result { get; set; }
     }

     public class feed
     {
         public string feed_address { get; set; }
         public string updated { get; set; }
         public string favicon_text_color { get; set; }
         public int subs { get; set; }
         public string feed_link { get; set; }
         public bool favicon_fetching { get; set; }
         public string nt { get; set; }
         public string updated_seconds_ago { get; set; }
         public int num_subscribers { get; set; }
         public string feed_title { get; set; }
         public string favicon_fade { get; set; }
         public string exception_type { get; set; }
         public string exception_code { get; set; }
         public string favicon_color { get; set; }
         public bool active { get; set; }
         public string ng { get; set; }
         public int feed_opens { get; set; }
         public int id { get; set; }
         public bool has_exception { get; set; }
     } }

答案 1 :(得分:1)

使用jsonreader,使用json.net,您的示例应如下所示:

public class Feeds
{
    public bool authenticated;
    public string user;
    public Dictionary<string, Feed> feeds;


    public void ReadJson(JsonReader reader)
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.EndObject)
                break;

            if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "authenticated")
            {
                reader.Read();
                authenticated = (bool)reader.Value;
            }
            else if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "user")
            {
                reader.Read();
                user = (string)reader.Value;
            }
            else if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "feeds")
            {
                feeds = new Dictionary<string, Feed>();
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.EndObject)
                        break;

                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        string key = (string)reader.Value;
                        feeds.Add(key, Feed.ReadFromJson(reader));
                    }
                }

            }
        }
    }

    public static Feeds ReadFromJson(Stream stream)
    {
        using (StreamReader sr = new StreamReader(stream))
        {
            using (Newtonsoft.Json.JsonReader jsonReader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                Feeds feeds = new Feeds();
                feeds.ReadJson(jsonReader);
                return feeds;
            }
        }
    }
}

public class Feed
{
    public string feed_address;
    public string updated;

    public void ReadJson(JsonReader reader)
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.EndObject)
                break;

            if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "feed_address")
            {
                reader.Read();
                feed_address = (string)reader.Value;
            }
            else if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "updated")
            {
                reader.Read();
                updated = (string)reader.Value;
            }
        }
    }

    public static Feed ReadFromJson(JsonReader reader)
    {
        Feed feed = new Feed();
        feed.ReadJson(reader);
        return feed;
    }
}

答案 2 :(得分:1)

由于返回的Json字符串包含的96705,768840,768842,768843等名称不是有效的c#变量名,因此除非使用feeds字典,否则不能将字符串反序列化为类。因此,如果以dict["key"]访问对象的某些属性是不可避免的,那么为什么还要为声明类FeedResponsefeed而烦恼呢?只需使用Json.Net的JObjectJTokenJProperty,如下所示。

JObject rootObj =  JsonConvert.DeserializeObject(jstr) as JObject;
Console.WriteLine(
    "Authenticated:" + rootObj["authenticated"] + 
    " USER:"         + rootObj["user"] + 
    " RESULT:"       + rootObj["result"]);


foreach (JProperty feed in rootObj["feeds"])
{
    Console.WriteLine(feed.Name + " " +  feed.Value["feed_address"]);
}