将由对象列表组成的JSON响应反序列化为c#类



我正在使用NewsBlur API,它返回提要列表。响应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以获取提要响应时出现了错误。

任何指针,我做错了什么?

Feeds是一个Dictionary<int,Feed>不是一个List<Feed>(有键)。

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

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

edit2: full sample working:

 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; }
     } }

使用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;
    }
}

因为你返回的Json字符串包含像96705,768840,768842,768843这样的名字,这是无效的c#变量名,你不能反序列化你的字符串到一个类,除非你使用feeds的字典。所以,如果访问对象的某些属性作为dict["key"]是不可避免的,那么为什么要声明类FeedResponsefeed呢?只需使用Json。JObject, JToken, JProperty如下图

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"]);
}

相关内容

  • 没有找到相关文章

最新更新