How to Use JSON In C#?

Working with JSON in C# involves serializing objects to JSON format (serialization) and deserializing JSON strings to objects (deserialization). This can be done using the built-in `System.Text.Json` namespace in .NET Core/.NET 5+ or third-party libraries like Newtonsoft.Json (Json.NET). Here’s how you can work with JSON using both approaches:

### Using System.Text.Json (Available in .NET Core 3.0+ and .NET 5+):

1. Serialization:
To serialize an object to JSON format, you can use the `JsonSerializer.Serialize` method:

using System;
using System.Text.Json;
class Program
{
static void Main()
{
var obj = new { Name = "John", Age = 30 };
string json = JsonSerializer.Serialize(obj);
Console.WriteLine(json); // Output: {"Name":"John","Age":30}
}
}

2. Deserialization:
To deserialize a JSON string to an object, you can use the `JsonSerializer.Deserialize` method:

using System;
using System.Text.Json;
class Program
{
static void Main()
{
string json = "{\"Name\":\"John\",\"Age\":30}";
var obj = JsonSerializer.Deserialize<MyClass>(json);
Console.WriteLine($"Name: {obj.Name}, Age: {obj.Age}"); // Output: Name: John, Age: 30
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}

### Using Newtonsoft.Json (Json.NET):

1. Serialization:
To serialize an object to JSON format using Json.NET, you can use the `JsonConvert.SerializeObject` method:

using System;
using Newtonsoft.Json;
class Program
{
static void Main()
{
var obj = new { Name = "John", Age = 30 };
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json); // Output: {"Name":"John","Age":30}
}
}

2. Deserialization:
To deserialize a JSON string to an object using Json.NET, you can use the `JsonConvert.DeserializeObject` method:

using System;
using Newtonsoft.Json;
class Program
{
static void Main()
{
string json = "{\"Name\":\"John\",\"Age\":30}";
var obj = JsonConvert.DeserializeObject<MyClass>(json);
Console.WriteLine($"Name: {obj.Name}, Age: {obj.Age}"); // Output: Name: John, Age: 30
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}

Choose the approach that best fits your project requirements and preferences. `System.Text.Json` is preferred for new .NET projects, while Json.NET remains a popular choice with a rich feature set and extensive community support.