我如何反序列化包含在json对象中的这个包含JSON的数组?

时间:2017-02-13 17:15:58

标签: c# json

我在论坛和许多教程上尝试了很多答案,以反序列化json对象中包含的json数组..但对我的情况没什么帮助。

我正试图从我的wordpress演示网站反序列化这个json:https://mahdii.000webhostapp.com/?wpapi=get_posts&dev=1

我想获得帖子名称和作者昵称。

我所尝试的是:

string json = new WebClient().DownloadString("https://mahdii.000webhostapp.com/?wpapi=get_posts&dev=1");
Console.WriteLine(json);
var deserialize_post = JsonConvert.DeserializeObject<List<RootObject>>(json);

我的班级:

public class Author
{
    public string id { get; set; }
    public string slug { get; set; }
    public string name { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string nickname { get; set; }
    public string url { get; set; }
    public string description { get; set; }
    public string gravatar { get; set; }
}

public class Post
{
    public string id { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
    public string url { get; set; }
    public string status { get; set; }
    public string title { get; set; }
    public string title_plain { get; set; }
    public string date { get; set; }
    public string modified { get; set; }
    public string excerpt { get; set; }
    public string parent { get; set; }
    public List<object> category { get; set; }
    public List<object> tag { get; set; }
    public List<Author> author { get; set; }
    public string comment_count { get; set; }
    public string comment_status { get; set; }
}

public class RootObject
{
    public List<Post> posts { get; set; }
}

我在deserialize_post得到null我想我做错了如果有人可以帮助我,我需要帮助。

谢谢,

1 个答案:

答案 0 :(得分:1)

我做了一个dotnetfiddle示例来修复序列化问题:

https://dotnetfiddle.net/kpnYv0

基本上,我拿走了你的数据(你的网站目前正在拥抱死亡)并将其置于以下逻辑中:

public static void Main()
{
    string json = new WebClient().DownloadString("https://mahdii.000webhostapp.com/?wpapi=get_posts&dev=1");

    var deserializePost = JsonConvert.DeserializeObject<RootObject>(json);
    var postInfo = deserializePost
        .posts
        .Select(p => new 
                { 
                    Name = p.title_plain, 
                    AuthorNicknames = p
                        .author
                        .Select(a => a.nickname) 
                });

    Console.WriteLine(postInfo.Count());
}

我只将特定请求的数据投射到postInfo变量中。您会发现每个帖子可以有多个作者,因此AuthorNicknames的{​​{1}}属性也是IEnumerable。

对于其他任何想要帮助的人,这里是网站返回的JSON:

postInfo