如何将JSON反序列化为此POCO类?

时间:2013-11-21 01:04:04

标签: c# json serialization

ERROR:

无法将类型'UserItem'隐式转换为'RootObject'

如何将JSON反序列化为此POCO类?

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

public static UserItem DownloadJSONString(string urlJson)
{
    using (WebClient wc = new WebClient())
    {
        var json = wc.DownloadString(urlJson);
        UserItem userItems = JsonConvert.DeserializeObject<RootObject>(json);

        return userItems;
    }            
}

我有点被困在这里

这里是我的Json:

{
    "meta":
    {
        "status":200,
        "resultSet":
        {
            "id":"05"
        },
        "pagination":
        {
            "count":2,
            "pageNum":1,
            "pageSize":2
        }
    },
    "results":   
    {
        "id":0,
        "name":
        "title",
        "items":
        [
            {
                "id":0,
                "name":"English",
                "title":"English",
            },
            {
                "id":0,
                "name":"Spanish",
                "title":"Spanish;",
            }
        ]
    }
}

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

public class ResultSet
{
    public string id { get; set; }
}

public class Pagination
{
    public int count { get; set; }
    public int pageNum { get; set; }
    public int pageSize { get; set; }
}

public class Meta
{
    public int status { get; set; }
    public ResultSet resultSet { get; set; }
    public Pagination pagination { get; set; }
}

public class Item
{
    public int id { get; set; }
    public string name { get; set; }
    public string title { get; set; }
}

public class Results
{
    public int id { get; set; }
    public string name { get; set; }
    public List<Item> items { 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; }
}

1 个答案:

答案 0 :(得分:6)

你走了:

var root = JsonConvert.DeserializeObject<RootObject>(json);
var userItem = root.results.items
                           .Select(i => new UserItem
                           {
                               id = i.id,
                               name = i.name,
                               title = i.title
                           }).FirstOrDefault();

return userItem;

如您所知,您不能只将Item类转换为UserItem,但您可以构建一个。这里需要注意的一点是,显然如果你只想要归还一个,你就必须抓住一个。在这里,我抓住了第一个或默认。如果列表为空,则默认值为null