使用嵌套选择将JSON反序列化为POCO类 [英] Deserialize JSON into POCO class with Nested Select

查看:73
本文介绍了使用嵌套选择将JSON反序列化为POCO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我提出的问题的继续

my question is continuation of what i have asked here

我只是试图将json数据反序列化为C#自定义poco类,如下所示,这是我到目前为止所做的;

I'm simply trying to deserilize json data into C# custom poco class as shown below and here is what i have done so far;

public static UserItem DownloadJSONString(string urlJson)
{
    var root = JsonConvert.DeserializeObject<RootObject>(json);
    var userItem = root.results
                       .Select(i => new UserItem
                       {
                           id = i.id,
                           name = i.name,
                           title = i.title,

                           //tried using `Any` but does not seems work...
                           audience = (from _tag in root.results.SelectMany(x => x.tags) //<<<
                                       select new Audience { id = _tag.Id .....}).ToList()

                       }).ToList();

      return userItem;          
}

这是我的json对象(从json生成为c#类)

public class Tags
{
   public List<object> audience { get; set; }
}    

public class Results
{
    public int id { get; set; }
    public string name { get; set; }
    public Tags tags { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Results results { get; set; }
}

这是我简单的UserItem POCO课

Here is my simple UserItem POCO class

public class UserItem 
{
    public int id { get; set; }
    public string name { get; set; }
    public string title { get; set; }
    public Audience audience { get; set; }
}

public class Audience 
{
    public int id { get; set; }
    public string name { get; set; }
}

推荐答案

就像所有其他方法一样,为其构建一个类,并将其反序列化为该类:

Just like all of the others, build a class for it and it will be deserialized into it:

public class TagAudience
{
    public string id { get; set; }
    public string name { get; set; }
}

,然后使用List<TagAudience>代替Tags类中的List<object>.最后,当您想要了解这些内容时:

and then instead of List<object> in the Tags class, use List<TagAudience>. Finally, when you want to get to those:

audience = i.Tags.audience
    .Select(ta => new Audience
    {
        id = ta.id,
        name = ta.name
    }).FirstOrDefault()

这篇关于使用嵌套选择将JSON反序列化为POCO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆