Press "Enter" to skip to content

How to create classes from JSON data files in C#

If you have a JSON data file and would like to quickly build classes you can deserialize the data into, Visual Studio has a simple way for you to do this – without manually creating the properties.

Let’s say we want to build a class to hold the data in this config.json file:

{
  "AppTitle": "My Cool Program",
  "StartMode": "FullScreen",
  "Languages": [
    {
      "Code": "EN",
      "Description": "English"
    },
    {
      "Code": "ES",
      "Description": "Spanish"
    }
  ] 
}

Create a new class. In this example, I’ll name the class ConfigValues.cs.

Delete everything from the file, except for the namespace declaration.

namespace Workbench.Models;

Highlight all the data in the JSON file and copy it to the clipboard (Ctrl-C). Go back into the empty class file (ConfigValues.cs) and put your cursor on a blank line.

In the Visual Studio menu, select Edit -> Paste Special -> Paste JSON as Classes. Notice that there is also a menu option to build classes from XML, in case the data you want to deserialize is in XML.

That produces this class:

namespace Workbench.Models;
public class Rootobject
{
    public string AppTitle { get; set; }
    public string StartMode { get; set; }
    public Language[] Languages { get; set; }
}
public class Language
{
    public string Code { get; set; }
    public string Description { get; set; }
}

Visual Studio can’t determine what the root class name should be. So, it defaults the class name to “Rootobject”. Rename the class to the name you want to use – in this case, ConfigValues.

Notice that the Visual Studio create a Language class for the child JSON data. You may want to separate the Language class definition into its own file, but you can also leave it in the ConfigValues.cs file, if you choose.

Visual Studio also sets datatypes for multiple values as arrays. You may want to convert this to a List<T>, or some other form of collection. In this case, I’ll convert the Languages property from a Language array to a List<Language>.

namespace Workbench.Models;
public class ConfigValues
{
    public string AppTitle { get; set; }
    public string StartMode { get; set; }
    public List<Language> Languages { get; set; }
}
public class Language
{
    public string Code { get; set; }
    public string Description { get; set; }
}

And now, you have a class (or multiple classes) you can use to deserialize the JSON data into, for use in your program as objects.

    Leave a Reply

    Your email address will not be published.

    This site uses Akismet to reduce spam. Learn how your comment data is processed.