The Best C# Deserializer To Convert JSON To An Object

The Best C# Deserializer To Convert JSON To An Object Banner

Introduction

In C#, we can use JSON to communicate data to and from applications. It is a string formatted with quotes It can be a web application to a backend service or REST endpoint. JSON is the format is a standardized format that doesn't require another .NET application on the other end. JSON is also considered lightweight and can be easily parsed. This gives you the flexibility to work with different programming languages on the application. So we need to understand the types and line them up with C# object to deserialize.

Video With Examples

Summary Table

Analysis TypeJsonSerializer DeserializeJSON.NET DeserializeObject
Rank12
Speed Test2569ms4801ms
.NET Version Available>= .NET 5 | >= .NET Framework 4.6.2 | >= .NET Standard 2.0 | >= .NET Core 2.1 >= .NET Standard 2.0 | >= .NET 5 | Silverlight | Windows Phone | Windows 8 Store
NamespaceSystem.Text.JsonNewtonsoft.Json
Lines Of Code11
Thread SafeYesYes

Unsupported JSON Deserializers

.NET had provided a lot of different options to convert a JSON to an object but it is now down to two choices. Microsoft has phased out support for the vast majority of these other ways to deserialize a JSON. We'll go through each one and see how they compare.

I also looked into other ways to JSON implementations that were scattered across .NET at various points in time but they no longer work or are not supported. Below is a list of old JSON implementations no longer supported.

Json.Decode in the System.Web.Helpers namespace does not work with the .NET framework and is restricted to ASP.NET Web Pages.

JsonQueryStringConverter.ConvertStringToValue in System.ServiceModel.Web didn't work with .NET latest. It has the latest support was .NET 4.8.1.

JavaScriptSerializer.Deserialize is only supported up to .NET 4.8.1 and Microsoft recommends not using it but rather using JsonSerializer in the System.Text.Json namespace for greater than 4.7.2 and for earlier versions to use JSON.NET.

System.Json was designed for Silverlight and is no longer supported for many years.

Windows.Data.Json JsonValue is very specific to Windows 8.x and Windows phone 8.x development

Third-Party Deserializers Not Considered

Jil is considered to be a fast JSON deserializer but there haven't been any updates in years so it makes me think that it isn't supported anymore. You don't want to be using a library that isn't supported in case you run into issues then may not be able to get around those.

Utf8Json has over 27 million downloads yet it hasn't been updated since 2018.

JsonSerializer Deserialize Method

JSON Serializer Deserialize Method Chart

C# has consolidated its latest JSON deserializer into the System.Text.Json namespace. It is considered Microsoft's stated go-to method for converting a JSON to an object.

Be aware that the property names are case-sensitive. Any constructors that are not public will be ignored. Watch out that comments in the JSON and any trailing commas will throw errors. There are options for all this. For this method, the maximum nested object depth is 64. This method was designed with thread safety in mind.

Below are some examples deserializing of various .NET types and a custom class with these building blocks you need to create any JSON.

Microsoft recommends using this method for greater than .NET 4.7.2.

JsonSerializer Deserialize Various Types Code Example

JSON Serializer Deserialize Syntax

This calls a simple one-line method. You need to provide the type of object to convert the JSON string too. Then pass the string to the method.

using System.Text.Json;

// Deserialize string
//raw JSON:"Hello, World!"
string jsonString = "\"Hello, World!\"";
string deserializedString = JsonSerializer.Deserialize<string>(jsonString);
Console.WriteLine(deserializedString);

// Deserialize int
//raw JSON:42
string jsonInt = "42";
int deserializedInt = JsonSerializer.Deserialize<int>(jsonInt);
Console.WriteLine(deserializedInt);

// Deserialize char
//raw JSON:"A"
string jsonChar = "\"A\"";
char deserializedChar = JsonSerializer.Deserialize<char>(jsonChar);
Console.WriteLine(deserializedChar);

// Deserialize bool
//raw JSON:true
string jsonBool = "true";
bool deserializedBool = JsonSerializer.Deserialize<bool>(jsonBool);
Console.WriteLine(deserializedBool);

// Deserialize float
//raw JSON:3.14
string jsonFloat = "3.14";
float deserializedFloat = JsonSerializer.Deserialize<float>(jsonFloat);
Console.WriteLine(deserializedFloat);

// Deserialize double
//raw JSON:2.71828
string jsonDouble = "2.71828";
double deserializedDouble = JsonSerializer.Deserialize<double>(jsonDouble);
Console.WriteLine(deserializedDouble);

// Deserialize List<string>
//raw JSON:["apple","banana","cherry"]
string jsonList = "[\"apple\", \"banana\", \"cherry\"]";
List<string> deserializedList = JsonSerializer.Deserialize<List<string>>(jsonList);
foreach (string item in deserializedList)
{
    Console.WriteLine(item);
}

// Deserialize Dictionary<string, int>
//raw JSON:{"one":1,"two":2,"three":3}
string jsonDictionary = "{\"one\": 1, \"two\": 2, \"three\": 3}";
Dictionary<string, int> deserializedDictionary = JsonSerializer.Deserialize<Dictionary<string, int>>(jsonDictionary);
foreach (KeyValuePair<string, int> pair in deserializedDictionary)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

// Deserialize array
//raw JSON:[1,2,3,4,5]
string jsonArray = "[1, 2, 3, 4, 5]";
int[] deserializedArray = JsonSerializer.Deserialize<int[]>(jsonArray);
foreach (int item in deserializedArray)
{
    Console.WriteLine(item);
}

JsonSerializer Deserialize Various Types Code Output

Hello, World!
42
A
True
3.14
2.71828
apple
banana
cherry
one: 1
two: 2
three: 3
1
2
3
4
5

JsonSerializer Deserialize Class Code Example

This puts it all together using all previous types and combines it into a class.

Raw JSON Form For Class
{
  "Name": "John Doe",
  "Age": 18,
  "Grade": "A",
  "IsPresent": true,
  "GPA": 3.8,
  "Height": 170.5,
  "Grades": {
    "Math": 90,
    "Science": 85,
    "English": 92
  },
  "Subjects": [
    "Math",
    "Science",
    "English"
  ],
  "CustomClasses": [
    {
      "ClassName": "History",
      "ClassId": 101
    },
    {
      "ClassName": "Art",
      "ClassId": 102
    }
  ]
}
C# Code
using System.Text.Json;
//JSON can be assigned as a string by the following syntax
string json = "{\r\n  \"Name\": \"John Doe\",\r\n  \"Age\": 18,\r\n  \"Grade\": \"A\",\r\n  \"IsPresent\": true,\r\n  \"GPA\": 3.8,\r\n  \"Height\": 170.5,\r\n  \"Grades\": {\r\n    \"Math\": 90,\r\n    \"Science\": 85,\r\n    \"English\": 92\r\n  },\r\n  \"Subjects\": [\r\n    \"Math\",\r\n    \"Science\",\r\n    \"English\"\r\n  ],\r\n  \"CustomClasses\": [\r\n    {\r\n      \"ClassName\": \"History\",\r\n      \"ClassId\": 101\r\n    },\r\n    {\r\n      \"ClassName\": \"Art\",\r\n      \"ClassId\": 102\r\n    }\r\n  ]\r\n}";

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonSerializer.Deserialize<Student>(json);//Convert JSON String to an object

PrintDeseralizedStudentObject(deserializedJSON);


void PrintDeseralizedStudentObject(Student deserializedJSON)
{
    // Accessing the deserialized object's properties
    Console.WriteLine("\nDeserialized Object:");
    Console.WriteLine("Name: " + deserializedJSON.Name);
    Console.WriteLine("Age: " + deserializedJSON.Age);
    Console.WriteLine("Grade: " + deserializedJSON.Grade);
    Console.WriteLine("IsPresent: " + deserializedJSON.IsPresent);
    Console.WriteLine("GPA: " + deserializedJSON.GPA);
    Console.WriteLine("Height: " + deserializedJSON.Height);

    Console.WriteLine("\nGrades:");
    foreach (var grade in deserializedJSON.Grades)
    {
        Console.WriteLine(grade.Key + ": " + grade.Value);
    }

    Console.WriteLine("\nSubjects:");
    foreach (var subject in deserializedJSON.Subjects)
    {
        Console.WriteLine(subject);
    }

    Console.WriteLine("\nCustom Classes:");
    foreach (var customClass in deserializedJSON.CustomClasses)
    {
        Console.WriteLine("Class Name: " + customClass.ClassName);
        Console.WriteLine("Class ID: " + customClass.ClassId);
        Console.WriteLine();
    }
}
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public char Grade { get; set; }
    public bool IsPresent { get; set; }
    public float GPA { get; set; }
    public double Height { get; set; }
    public Dictionary<string, int> Grades { get; set; }
    public List<string> Subjects { get; set; }
    public CustomClass[] CustomClasses { get; set; }

    public Student(string name, int age, char grade, bool isPresent, float gpa, double height,
                   Dictionary<string, int> grades, List<string> subjects, CustomClass[] customClasses)
    {
        Name = name;
        Age = age;
        Grade = grade;
        IsPresent = isPresent;
        GPA = gpa;
        Height = height;
        Grades = grades;
        Subjects = subjects;
        CustomClasses = customClasses;
    }
}

public class CustomClass
{
    public string ClassName { get; set; }
    public int ClassId { get; set; }

    public CustomClass(string className, int classId)
    {
        ClassName = className;
        ClassId = classId;
    }
}
Code Output
Deserialized Object:
Name: John Doe
Age: 18
Grade: A
IsPresent: True
GPA: 3.8
Height: 170.5

Grades:
Math: 90
Science: 85
English: 92

Subjects:
Math
Science
English

Custom Classes:
Class Name: History
Class ID: 101

Class Name: Art
Class ID: 102
C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

JSON.NET DeserializeObject Method

JSON.NET Deserialize Object Chart

JSON.NET has been around for some time, it grew out of a library when there weren't any libraries to work with JSON on the .NET platform at the time. It boasts that is the most popular .NET Nuget package with over 1 billion downloads. I have also used it during my career so it is well-known and reliable. It has broad support across the .NET platform and is even compatible with a none supported .NET platform like Silverlight. This is where I first encountered JSON.NET when I was working on a Silverlight project. It was indeed to go to method and our company continued to use it for some time after that.

It is feature-rich and has wide community support so you might want to check out its additional features if you considering using it in your application over the other options.

Microsoft recommends using this method for .NET 4.7.2 and earlier.

This method is considered thread safe with the later versions.

JSON.NET DeserializeObject Various Example

JSON.NET Deserialize Object Syntax

This also has a simple one-line code implementation that takes in the return type and a JSON string to parse. You must ensure that the JSON is in the proper format or else an exception will occur.

using Newtonsoft.Json;

//JSON can be assigned as a string by the following syntax
string jsonStudent = "{\r\n  \"Name\": \"Alex\",\r\n  \"Age\": 16,\r\n  \"Grade\": \"A\",\r\n  \"IsPresent\": true,\r\n  \"GPA\": 2.1,\r\n  \"Height\": 1.75,\r\n  \"Grades\": {\r\n    \"Math\": 48,\r\n    \"Science\": 72,\r\n    \"English\": 83\r\n  },\r\n  \"Subjects\": [\r\n    \"Math\",\r\n    \"Science\",\r\n    \"English\"\r\n  ],\r\n  \"CustomClasses\": [\r\n    {\r\n      \"ClassName\": \"History\",\r\n      \"ClassId\": 138\r\n    },\r\n    {\r\n      \"ClassName\": \"Art\",\r\n      \"ClassId\": 256\r\n    }\r\n  ]\r\n}";

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonConvert.DeserializeObject<Student>(jsonStudent);//Convert JSON String to an object

PrintDeseralizedStudentObject(deserializedJSON);

...
Code Output
Deserialized Object:
Name: Alex
Age: 16
Grade: A
IsPresent: True
GPA: 2.1
Height: 1.75

Grades:
Math: 48
Science: 72
English: 83

Subjects:
Math
Science
English

Custom Classes:
Class Name: History
Class ID: 138

Class Name: Art
Class ID: 256

Speed Test

This is a test to see how fast the JSON deserializers can create the object. It takes an average of 10 tests. Each test there 100 loops of the test function. Each test function will have 10000 JSONs to convert into objects.

Speed Test Video

JsonSerializer Deserialize Speed Test Code

void TestMethod(List<string> jsonList)
{
    foreach (string json in jsonList)
    {
        Student student = JsonSerializer.Deserialize<Student>(json);//Convert JSON String to an object
    }
}

JSON.NET DeserializeObject Speed Test Code

void TestMethod(List<string> jsonList)
{
    foreach (string json in jsonList)
    {
        Student deserializedJSON = JsonConvert.DeserializeObject<Student>(json);//Convert JSON String to an object
    }
}
JsonSerializer Deserialize Code Output
Test 1: 0m 2s 856ms
Test 2: 0m 2s 539ms
Test 3: 0m 2s 521ms
Test 4: 0m 2s 595ms
Test 5: 0m 2s 540ms
Test 6: 0m 2s 517ms
Test 7: 0m 2s 546ms
Test 8: 0m 2s 535ms
Test 9: 0m 2s 514ms
Test 10: 0m 2s 519ms
JsonSerializer Deserialize Average Speed:2569ms, In 10 Tests
JSON.NET DeserializeObject Code Output
Test 1: 0m 5s 168ms
Test 2: 0m 4s 748ms
Test 3: 0m 4s 808ms
Test 4: 0m 4s 754ms
Test 5: 0m 4s 803ms
Test 6: 0m 4s 764ms
Test 7: 0m 4s 700ms
Test 8: 0m 4s 723ms
Test 9: 0m 4s 819ms
Test 10: 0m 4s 717ms
JSON.NET DeserializeObject Average Speed:4801ms, In 10 Tests
JsonSerializer Deserialize Code Test Code

using System;
using System.Diagnostics;
using System.Text;
using System.Text.Json;

int numberOfTests = 10;//Number of tests 
int numberOfFunctionCalls = 100;//Number of function calls made per test
int numberOfObjectsToCreate = 10000;//Number test objects
string testName = "JsonSerializer Deserialize";//Test name to print to average

void TestMethod(List<string> jsonList)
{
    foreach (string json in jsonList)
    {
        Student student = JsonSerializer.Deserialize<Student>(json);
    }
}

List<double> testSpeedList = new List<double>();
for (int testIndex = 0; testIndex < numberOfTests; testIndex++)
{
    testSpeedList.Add(StartTest(testIndex));
}
Console.WriteLine($"{testName} Average Speed:{Math.Round(testSpeedList.Average())}ms, In {numberOfTests} Tests");

double StartTest(int testIndex)
{
    Stopwatch stopwatch = new Stopwatch();
    List<string> testData = GetJSONData();//Get intial random generated data
    for (int i = 0; i < numberOfFunctionCalls; i++)
    {
        stopwatch.Start();//Start the Stopwatch timer
        TestMethod(testData);//
        stopwatch.Stop();//Stop the Stopwatch timer
    }
    stopwatch.Stop();//Stop the Stopwatch timer
    Console.WriteLine($"Test {testIndex + 1}: {stopwatch.Elapsed.Minutes}m {stopwatch.Elapsed.Seconds}s {stopwatch.Elapsed.Milliseconds}ms");
    return stopwatch.Elapsed.TotalMilliseconds;
}

List<string> GetJSONData()
{
    List<string> testData = new List<string>();

    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        Student student = GenerateRandomStudent();
        string testJson = ConvertToString(student);
        string json = JsonSerializer.Serialize(student);
        testData.Add(json);
    }
    return testData;
}

static Student GenerateRandomStudent()
{
    Random random = new Random();
    string[] names = { "John", "Jane", "Mike", "Emily", "Alex" };
    char[] grades = { 'A', 'B', 'C', 'D', 'F' };

    string randomName = names[random.Next(names.Length)];
    int randomAge = random.Next(14, 19);
    char randomGrade = grades[random.Next(grades.Length)];
    bool randomIsPresent = random.Next(2) == 0 ? true : false;
    float randomGPA = random.Next(20, 41) / 10f;
    double randomHeight = random.Next(150, 190) / 100.0;

    Dictionary<string, int> randomGrades = new Dictionary<string, int>
        {
            { "Math", random.Next(40, 101) },
            { "Science", random.Next(40, 101) },
            { "English", random.Next(40, 101) }
        };

    List<string> randomSubjects = new List<string>
        {
            "Math", "Science", "English"
        };

    CustomClass[] randomCustomClasses = new CustomClass[]
    {
            new CustomClass("History", random.Next(101, 201)),
            new CustomClass("Art", random.Next(201, 301))
        };

    return new Student(randomName, randomAge, randomGrade, randomIsPresent, randomGPA, randomHeight, randomGrades, randomSubjects, randomCustomClasses);
}


static string ConvertToString(Student student)
{
    var options = new JsonSerializerOptions
    {
        WriteIndented = true
    };

    using (var stream = new MemoryStream())
    {
        using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
        {
            JsonSerializer.Serialize(writer, student, options);
        }

        return Encoding.UTF8.GetString(stream.ToArray());
    }
}
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public char Grade { get; set; }
    public bool IsPresent { get; set; }
    public float GPA { get; set; }
    public double Height { get; set; }
    public Dictionary<string, int> Grades { get; set; }
    public List<string> Subjects { get; set; }
    public CustomClass[] CustomClasses { get; set; }

    public Student(string name, int age, char grade, bool isPresent, float gpa, double height,
                   Dictionary<string, int> grades, List<string> subjects, CustomClass[] customClasses)
    {
        Name = name;
        Age = age;
        Grade = grade;
        IsPresent = isPresent;
        GPA = gpa;
        Height = height;
        Grades = grades;
        Subjects = subjects;
        CustomClasses = customClasses;
    }
}

public class CustomClass
{
    public string ClassName { get; set; }
    public int ClassId { get; set; }

    public CustomClass(string className, int classId)
    {
        ClassName = className;
        ClassId = classId;
    }
}

Feature Comparison

Since Newtonsoft.JSON has been around much longer it has more features compared to JsonSerializer but I'll show how to use each feature from both methods.

This is not an exhaustive list of all the features between these two methods. A more complete list can be found here.

All cases use the following class and have the following output unless otherwise stated.

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public char Grade { get; set; }
    public bool IsPresent { get; set; }
    public float GPA { get; set; }
    public double Height { get; set; }
    public Dictionary<string, int> Grades { get; set; }
    public List<string> Subjects { get; set; }
    public CustomClass[] CustomClasses { get; set; }
}

public class CustomClass
{
    public string ClassName { get; set; }
    public int ClassId { get; set; }
}

Output for each of the cases is the following unless otherwise stated.

Deserialized Object:
Name: John Doe
Age: 18
Grade: A
IsPresent: True
GPA: 0
Height: 170.5

Grades:
math: 90
science: 85
english: 92

Subjects:
Math
Science
English

Custom Classes:
Class Name: History
Class ID: 101

Class Name: Art
Class ID: 102

Case-Insensitive

JsonSerializer default is case sensitive which helps to improve speed. While NewTonsoft.JSON is case-insensitive by default.

Case-insensitive property names can be enabled by using the JsonSerializerOptions and passing it to the method.

Case-Insensitive Video

Case-Insensitive JsonSerializer
//Case-insensitive
using System.Text.Json;
//JSON can be assigned as a string
string json = "{\"name\":\"john doe\",\"age\":18,\"grade\":\"a\",\"ispresent\":true,\"gpa\":3.8,\"height\":170.5,\"grades\":{\"math\":90,\"science\":85,\"english\":92},\"subjects\":[\"math\",\"science\",\"english\"],\"customclasses\":[{\"classname\":\"history\",\"classid\":101},{\"classname\":\"art\",\"classid\":102}]}";

JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.PropertyNameCaseInsensitive = true;//Enable case insenstive property names

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonSerializer.Deserialize<Student>(json, jsonSerializerOptions);//Convert JSON String to an object
...
Case-Insensitive JSON.NET
//Case-insensitive
using System.Text.Json;
//JSON can be assigned as a string
string json = "{\"name\":\"john doe\",\"age\":18,\"grade\":\"a\",\"ispresent\":true,\"gpa\":3.8,\"height\":170.5,\"grades\":{\"math\":90,\"science\":85,\"english\":92},\"subjects\":[\"math\",\"science\",\"english\"],\"customclasses\":[{\"classname\":\"history\",\"classid\":101},{\"classname\":\"art\",\"classid\":102}]}";

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonConvert.DeserializeObject<Student>(json);//Convert JSON String to an object
...

Camel Case Property Names

Camel case is when the first letter of the first word is lower case and then all following word's first letters are upper case. The JSON can be camel case when the class properties don't need to be changed. We'll use JsonSerializerOptions to set the JSON properties.

Camel Case Property Names Video

Camel Case JsonSerializer
//Camel case
using System.Text.Json;
//JSON can be assigned as a string
string json = "{\"name\":\"John Doe\",\"age\":18,\"grade\":\"A\",\"isPresent\":true,\"gPA\":3.8,\"height\":170.5,\"grades\":{\"math\":90,\"science\":85,\"english\":92},\"subjects\":[\"Math\",\"Science\",\"English\"],\"customClasses\":[{\"className\":\"History\",\"classId\":101},{\"className\":\"Art\",\"classId\":102}]}";

JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonSerializer.Deserialize<Student>(json, jsonSerializerOptions);//Convert JSON String to an object
...
Camel Case JSON.NET
//camel case
using Newtonsoft.Json;
//JSON can be assigned as a string
string json = "{\"name\":\"John Doe\",\"age\":18,\"grade\":\"A\",\"isPresent\":true,\"gPA\":3.8,\"height\":170.5,\"grades\":{\"math\":90,\"science\":85,\"english\":92},\"subjects\":[\"Math\",\"Science\",\"English\"],\"customClasses\":[{\"className\":\"History\",\"classId\":101},{\"className\":\"Art\",\"classId\":102}]}";

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonConvert.DeserializeObject<Student>(json);//Convert JSON String to an object
...

Allow Comments, Trailing Commas With JsonSerializer Video

Allow Comments, Trailing Commas With JsonSerializer

//Allow comments, trailing commas
using System.Text.Json;

//JSON can be assigned as a string
string json = "{\"Name\":\"John Doe\", // name comment\r\n \"Age\":18,\"Grade\":\"A\",\"IsPresent\":true,\"GPA\":3.8,\"Height\":170.5,\"Grades\":{\"Math\":90,\"Science\":85,\"English\":92},\"Subjects\":[\"Math\",\"Science\",\"English\"],\"CustomClasses\":[{\"ClassName\":\"History\",\"ClassId\":101},{\"ClassName\":\"Art\",\"ClassId\":102}, /* comment for multiline */]}";

JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
jsonSerializerOptions.AllowTrailingCommas = true;


// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonSerializer.Deserialize<Student>(json, jsonSerializerOptions);//Convert JSON String to an object
Allow Comments, Trailing Commas With JSON.NET
//Allow comments, trailing commas
using Newtonsoft.Json;

//JSON can be assigned as a string
string json = "{\"Name\":\"John Doe\", // name comment\r\n \"Age\":18,\"Grade\":\"A\",\"IsPresent\":true,\"GPA\":3.8,\"Height\":170.5,\"Grades\":{\"Math\":90,\"Science\":85,\"English\":92},\"Subjects\":[\"Math\",\"Science\",\"English\"],\"CustomClasses\":[{\"ClassName\":\"History\",\"ClassId\":101},{\"ClassName\":\"Art\",\"ClassId\":102}, /* comment for multiline */]}";

// Deserializing the JSON string back to a Student object
Student deserializedJSON = JsonConvert.DeserializeObject<Student>(json);//Convert JSON String to an object

JSON Tips

You can get a class structure based on the JSON through Visual Studio.

Generate A Class Structure For Your JSON

Once you copy the JSON, then go to Visual Studio. Edit -> Past Special -> Past JSON as Classes will create the class structure for you. There's an example of the output. If I have the following JSON, visual studio will convert it into the following.

{"Name":"John Doe", "Age":18,"Grade":"A","IsPresent":true,"GPA":3.8,"Height":170.5,"Grades":{"Math":90,"Science":85,"English":92},"Subjects":["Math","Science","English"],"CustomClasses":[{"ClassName":"History","ClassId":101},{"ClassName":"Art","ClassId":102}]}

public class Rootobject
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Grade { get; set; }
    public bool IsPresent { get; set; }
    public float GPA { get; set; }
    public float Height { get; set; }
    public Grades Grades { get; set; }
    public string[] Subjects { get; set; }
    public Customclass[] CustomClasses { get; set; }
}

public class Grades
{
    public int Math { get; set; }
    public int Science { get; set; }
    public int English { get; set; }
}

public class Customclass
{
    public string ClassName { get; set; }
    public int ClassId { get; set; }
}

Conclusion

JsonSerializer Deserialize is the best JSON Deserializer method as it is the fastest based on my testing. It is almost twice as fast as the other method. It has native C# support there may not be a need for an additional library. There are options object to explore with other features. This is best used when you're working with .NET versions 4.7.2 and greater.

JSON.NET DeserializeObject is slower JsonSerializer Deserialize which is why it is in a second-place finish this time. It has been a reliable library and very easy to use for so long even when .NET didn't have native JSON deserializer support. It continues to be supported and it is best used when working with .NET 4.7.1 and lower.

If you want to change a object into a JSON then check out Serialization By Transforming Objects into A JSON String

Get Latest Updates