In previous article, we mentioned Lambda expression in C# (With Examples) but in this article, I have mentioned how we can convert C# Class into JSON string using console application example, which can be used to .NET or .NET Core.
So, create a new console application using Visual Studio 2019 in .NET Core 3 or above.
Once Visual Studio generates a Console application template, we will need to install 'NewtonSoft.JSON' nuget package, so navigate to Tools -> Nuget Package Manager -> Nuget Package Manager Console, then use the below command
Install-Package Newtonsoft.Json
Once, we have installed above package navigate to Program.cs and use the below C# Code, which has sample Student class with sub-class "Subject" and a sample data is added in "Main" method.
using Newtonsoft.Json;
using System;
public class Student
{
public string FirstName;
public string LastName;
public Subject subject;
}
public class Subject
{
public string Name { get; set; }
public string Class { get; set; }
}
namespace CSharpClassToJSON
{
class Program
{
static void Main(string[] args)
{
var obj = new Student
{
FirstName = "Vikram",
LastName = "Vaswani",
subject = new Subject
{
Name= "Science",
Class = "X"
}
};
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
}
}
}
Output:
{"FirstName":"Vikram","LastName":"Vaswani","subject":{"Name":"Science","Class":"X"}}
So, as you can see we were able to convert C# Class data into JSON string.
JSON to C# Class
Now, further if you want to deserialize data and convert JSON into C# Class, then you can add some code more
var classData = JsonConvert.DeserializeObject<Student>(json);
Console.WriteLine(classData.FirstName + " " + classData.LastName);
Which will give you output as
Vikram Vaswani
That's it, hope it helps.
You may also like to read:
Get First Character or Nth Character of string in C#
Convert string to char or char array in C#
Converting JSON to XML OR XML to JSON using C#
Foreach() vs Parallel.Foreach() in C#