JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. In C#, you can work with JSON data using the `System.Text.Json` or `Newtonsoft.Json` libraries.
Here’s how you can work with JSON data using both libraries:
## Using System.Text.Json library
1. Deserialize JSON to an object:
The `System.Text.Json` library provides classes and methods to deserialize JSON data into strongly typed objects. You can use the `JsonSerializer.Deserialize
“`csharp
using System.Text.Json;
// JSON string
string json = “{\”name\”:\”John\”,\”age\”:30}”;
// Deserialize JSON to object
var obj = JsonSerializer.Deserialize
// Define the class with properties that match the JSON structure
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
“`
2. Serialize an object to JSON:
You can use the `JsonSerializer.Serialize
“`csharp
using System.Text.Json;
// Create an object
var obj = new MyClass { Name = “John”, Age = 30 };
// Serialize object to JSON
string json = JsonSerializer.Serialize(obj);
// Output: {“name”:”John”,”age”:30}
// Define the class with properties that match the JSON structure
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
“`
## Using Newtonsoft.Json library
1. Deserialize JSON to an object:
The `Newtonsoft.Json` library provides a `JsonConvert.DeserializeObject
“`csharp
using Newtonsoft.Json;
// JSON string
string json = “{\”name\”:\”John\”,\”age\”:30}”;
// Deserialize JSON to object
var obj = JsonConvert.DeserializeObject
// Define the class with properties that match the JSON structure
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
“`
2. Serialize an object to JSON:
You can use the `JsonConvert.SerializeObject()` method to serialize an object to JSON.
“`csharp
using Newtonsoft.Json;
// Create an object
var obj = new MyClass { Name = “John”, Age = 30 };
// Serialize object to JSON
string json = JsonConvert.SerializeObject(obj);
// Output: {“name”:”John”,”age”:30}
// Define the class with properties that match the JSON structure
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
“`
Both libraries provide similar functionality for working with JSON data. You can choose either based on your preference and requirements.