How can I deserialize JSON into this POCO class?
c#, json, serialization
Solution
Here you go:
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;
As you already know, you can't just convert the `Item` class into a `UserItem`, but you can build one. One thing to note here is that obviously if you only want to return one you'll have to just grab one. Here I've grabbed the first or default. The default would be `null` if the list were empty for example.
Problem
ERROR: Cannot implicitly convert type 'UserItem' to 'RootObject' How can I deserialize JSON into this POCO class? 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) { using (WebClient wc = new WebClient()) { var json = wc.DownloadString(urlJson); UserItem userItems = JsonConvert.DeserializeObject<RootObject>(json); return userItems; } } ``` I'm kind of stuck here here my 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;", } ] } } ``` here is my json object (generate from json to c# class) ``` 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; } } ``` 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; } } ```