Click here to Skip to main content
15,887,432 members
Articles / Programming Languages / C#
Tip/Trick

Convert JSON to C# Classes using Paste JSON as Classes Feature

Rate me:
Please Sign up or sign in to vote.
2.58/5 (7 votes)
7 Apr 2023CPOL2 min read 9.9K   4   7   2
Convert JSON to C# classes in Visual Studio
This tip shows how to convert complex JSON to C# classes in Visual Studio.

Introduction

This tip shows how to convert complex JSON to C# classes in Visual Studio using the Paste JSON as Classes feature.  VS 2022 and .NET 7 is used in the examples below, however the Paste as JSON classes feature is also available in VS 2019.

Background

If you have complex JSON coming from an external feed or middleware and it needs to be deserialized to C# objects, but the C# classes do not exist, this tip will show how the JSON text can be used to create C# classes before it can be deserialized into these classes.

Using the Code

The code used in this tip can be found at Bitbucket here.

Create a C# console application in Visual Studio, and add a class file called myclasses.cs.

   Image 1

Remove the default internal class from myclasses.cs file.

Image 2

After the default class is removed, the file should appear as:

Image 3

We will leave the cursor position in between the two braces as this is where the generated C# classes will be inserted.

Here is the sample JSON which will be used for the conversion...

JavaScript
 {
   "Firstname":"John",
   "Surname":"Smith",
   "Email":"jsmith@hotmail.com",
   "ContactNumber":"07816912456",
   "AddressLine1":"564 Henley Street",
   "AddressLine2":"Islington",
   "Town":"London",
   "City":"London",
   "PostCode":"N1 0UY",
   "IsNewCustomer":false,
   "CustomerType":1,
   "Orders":[
      {
         "CustomerId":100,
         "OrderItems":[
            {
               "Id":1,
               "OrderId":101,
               "ProductId":5991,
               "Qty":1
            },
            {
               "Id":2,
               "OrderId":101,
               "ProductId":5992,
               "Qty":2
            }
         ],
         "Id":1,
         "Status":1,
         "DateCreated":"2023-04-07T09:57:39.6698184+01:00",
         "DateUpdate":"2023-04-07T09:57:39.6991824+01:00"
      }
   ],
   "Id":1,
   "DateCreated":"2023-04-07T09:57:39.7027728+01:00",
   "DateUpdate":"2023-04-07T09:57:39.7029128+01:00",
   "IsActive":true
}

The objective is to convert this into a class hierarchy as shown below...

Image 4

In order to create the C# classes, copy the JSON to the clipboard.

Then in Visual Studio, select Edit from the top bar, then select Paste JSON As Classes.

  Image 5

The myclasses.cs file will now show the result as below:

C#
namespace JSONTest
{
    public class Rootobject
    {
        public string Firstname { get; set; }
        public string Surname { get; set; }
        public string Email { get; set; }
        public string ContactNumber { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string Town { get; set; }
        public string City { get; set; }
        public string PostCode { get; set; }
        public bool IsNewCustomer { get; set; }
        public int CustomerType { get; set; }
        public Order[] Orders { get; set; }
        public int Id { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateUpdate { get; set; }
        public bool IsActive { get; set; }
    }

    public class Order
    {
        public int CustomerId { get; set; }
        public Orderitem[] OrderItems { get; set; }
        public int Id { get; set; }
        public int Status { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateUpdate { get; set; }
    }

    public class Orderitem
    {
        public int Id { get; set; }
        public int OrderId { get; set; }
        public int ProductId { get; set; }
        public int Qty { get; set; }
    }
}

The Rootobject is the top level class which will be renamed manually to Customer.

Now that we have the C# classes, the JSON can be populated by deserializing it into the class hierarchy of Customer.

In order to demonstrate this, a function is used to return JSON data which is then deserialized into the C# object model of customer/orders.

C#
public static string GetJsonData()
{
     return "{\"Firstname\":\"John\",\"Surname\":\"Smith\",\"Email\":\
               "jsmith@hotmail.com\",\"ContactNumber\":\"07816912456\",\
               "AddressLine1\":\"564 Henley Street\",\"AddressLine2\":\
               "Islington\",\"Town\":\"London\",\"City\":\"London\",\
               "PostCode\":\"N1 0UY\",\"IsNewCustomer\":false,\"CustomerType\
               ":1,\"Orders\":[{\"CustomerId\":100,\"OrderItems\
               ":[{\"Id\":1,\"OrderId\":101,\"ProductId\":5991,\
               "Qty\":1},{\"Id\":2,\"OrderId\":101,\"ProductId\":5992,\
               "Qty\":2}],\"Id\":1,\"Status\":1,\"DateCreated\":\
               "2023-04-07T09:57:39.6698184+01:00\",\"DateUpdate\":\
               "2023-04-07T09:57:39.6991824+01:00\"}],\"Id\":1,\
               "DateCreated\":\"2023-04-07T09:57:39.7027728+01:00\",\
               "DateUpdate\":\"2023-04-07T09:57:39.7029128+01:00\",\"IsActive\":true}";
}

The calling code...

C#
static void Main(string[] args)
{
     var customer =  GetData();
     Console.WriteLine(customer.Firstname + " " + customer.Surname);
     Console.ReadLine();
}

private static Customer GetData()
{
     var json = DataFeed.GetJsonData();

     var customer = JsonSerializer.Deserialize<Customer>(json);

     return customer;
}

Here, the JSON data from the GetJsonData method is deserialized into the top-level Customer object. A watch on this object shows the object hierarchy has been populated with the expected data.

   Image 6

The above shows Customer details, an array of Orders, and for each order, an array of OrderItems.

Points of Interest

The same steps can be followed to convert XML to C# classes.

History

  • v 1.0 - 09:30GMT 2023-04-05 Initial draft
  • v 1.1 - 10:45GMT 2023-04-07 Deserialization added
  • v 1.2 - 20:27GMT 2023-04-07 Repository link added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
Kuv Patel is a Senior Software Developer and Solutions Architect, specializing in .NET and Javascript frameworks development using MVC, ASP.NET, C#, WCF, Web API, Entity Framework, React, Angular.

Comments and Discussions

 
QuestionBroken Images Pin
Graeme_Grant7-Apr-23 11:58
mvaGraeme_Grant7-Apr-23 11:58 
AnswerRe: Broken Images Pin
Kuv Patel7-Apr-23 20:52
Kuv Patel7-Apr-23 20:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.