使用嵌套选择将JSON反序列化为POCO类

时间:2013-11-21 02:39:52

标签: c# json

我的问题是继续我所要求的here

我只是试图将json数据设置为C#自定义poco类,如下所示,这是我到目前为止所做的事情;

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课程

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

1 个答案:

答案 0 :(得分:0)

就像所有其他人一样,为它构建一个类,它将被反序列化为它:

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

然后使用List<object>而不是Tags类中的List<TagAudience>。最后,当你想要那些:

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