DESERIALIZEOBJECT WITH NEWTONSOFT LIST IN A LIST

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
JSON 
 2468  View(s)
Ratings:
Rate this:
Hi Expert,

First off, sorry for my bad English. Hi there, I am trying to deserialize json (with newtonsoft) to a list, which works great. But my only problem is that I need to put a list inside a list, if this is even possible. Why I want to do this is because I have a set of items with subitems in it. How do I put all of them in a nice sorted list? Here is some example code I made:

C# Code

var items = JsonConvert.DeserializeObject<List<Items>>(wc.DownloadString("http://localhost/index.php"));
foreach (var item in items)
{
    Console.WriteLine(item);
}

listItems.AddRange(items);

public class Items
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Genre { get; set; }
    public string Size { get; set; }
    public string Version { get; set; }
    public string Download_Link { get; set; }
    public string Description { get; set; }
}
JSON

[
    {
        "id": "1",
        "name": "Application 1",
        "genre": "Something",
        "description": "The description",
        "versions": [
            {
                "appid": "1",
                "version": "1",
                "patch_notes": "Release version.",
                "download_link": "http://localhost/downloads/application_1.zip",
                "size": 5120
            }
        ]
    }
]

My problem is that I can't seem to put the second array inside of the list with the items. I know I'm doing something wrong, but I can't seem to figure out what, could someone please help me with this? It would be very appreciated.

Thanks in advance for any recommendations or solutions.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: DeserializeObject with Newtonsoft list in a list

    Hi Ezra,


    In the JSON, Versions is an array. You'll have to model that object as well.

    Your model should look something like this

    public class Items
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Genre { get; set; }
        public string Description { get; set; }
        public List<Version> Versions { get; set; }
    }

    public class Version
    {
        public string Appid { get; set; }
        public string Version { get; set; }
        public string Patch_Notes { get; set; }
        public string Download_Link { get; set; }
        public int Size { get; set; }
    }

    Thanks in advance. 

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!