C# and JSON

If you need to use data formatted with the JSON standard, here is a simple trick to get started (but you can complicate it as you wish ;)). I use the Web Essentials extension and the NuGet package Json.NET. The JSON data file I use is this one: Example JSON File (source).

Here are the steps to take the JSON data, generate the necessary classes, download the data, and populate these new classes:

  • Install the Web Essentials extension
  • Create a new class file
  • Put a snippet or the entire JSON data into the clipboard (Copy or CTRL-C)
  • Right-click in the editor or go to the EDIT menu/Special Paste and select “Paste JSON as Classes”

image

This will create classes from the JSON code. In our example, this gives the following classes:

public class Rootobject
{
    public Items items { get; set; }
}

public class Items
{
    public Item[] item { get; set; }
}

public class Item
{
    public string id { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public float ppu { get; set; }
    public Batters batters { get; set; }
    public Topping[] topping { get; set; }
    public Fillings fillings { get; set; }
}

public class Batters
{
    public Batter[] batter { get; set; }
}

public class Batter
{
    public string id { get; set; }
    public string type { get; set; }
}

public class Fillings
{
    public Filling[] filling { get; set; }
}

public class Filling
{
    public string id { get; set; }
    public string name { get; set; }
    public float addcost { get; set; }
}

public class Topping
{
    public string id { get; set; }
    public string type { get; set; }
}

Next, we need to download this file from our application to display/process the data. To do this:

  • Add the NuGet package Json.NET
  • Add the following usings:
    • using Newtonsoft.Json;
    • using System.Net.Http;
  • Use HttpClient and Json.NET to fetch the JSON data and populate our classes
private static async Task<Rootobject> GetData()
{
    HttpClient client = new HttpClient();
    var response = await client.GetStringAsync("http://www.gabrielmongeon.com/public/blog/donuts.js");
    var root = JsonConvert.DeserializeObject<Rootobject>(response);

    return root;
}

There you go, you have a data structure filled with data from JSON. All that’s left is to find/create a data source and display/format this data in your application.

Happy coding!


See also