Generate C# Class From JSON in Visual Studio

Using Visual Studio 2012 or newer you can just “Special Paste” your JSON as C# classes.

Steps to Generate C# Class from JSON

  1. Copy your JSON content to the clipboard
  2. In file the editor, select the place where you want your classes to be pasted
  3. From the menu, select EDIT > Paste Special > Paste JSON As Classes

Check examples:

Generate C# Class from Simple JSON

The next JSON could be described as a simple Person class:
JSON to C# class in Visual Studio 2022

{"Id":1,"FirstName":"Brock","LastName":"Moore","DateOfBirth":"1997-12-15T22:48:41.8142892+02:00","FavouriteWebsite":"https://yarkul.com"}
public class Rootobject
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string FavouriteWebsite { get; set; }
}

 

Generated C# List(Array) of Persons from collection JSON

The next JSON is treated as an array of Person:

[{"Id":0,"FirstName":"Miranda","LastName":"Craig","DateOfBirth":"1999-12-01T00:00:00","FavouriteWebsite":null},
{"Id":1,"FirstName":"Alonzo","LastName":"Collins","DateOfBirth":"1975-10-08T00:00:00","FavouriteWebsite":null},
{"Id":2,"FirstName":"Sullivan","LastName":"Robles","DateOfBirth":"2000-11-15T00:00:00","FavouriteWebsite":null}]
public class Rootobject
{
    public Class1[] Property1 { get; set; }
}
public class Class1
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public object FavouriteWebsite { get; set; }
}

 

json collection to List in C#

Now you can simply change an array to list and rename it to more human names(Class1 to Person, and Class1[] Property1 to List Persons). You may also want to read my articles related to serialization:

Leave a Comment