JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate. In C#, the System.Text.Json
namespace provides powerful tools for working with JSON data.
Serialization is the process of converting an object into a JSON string. Here’s how you can serialize a simple C# object:
using System;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "Alice", Age = 30 };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
}
}
{"Name":"Alice","Age":30}
Deserialization is the reverse process where a JSON string is converted back into a C# object. Here’s how to do it:
using System;
using System.Text.Json;
class Program
{
static void Main()
{
string jsonString = "{"Name":"Bob","Age":25}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
Name: Bob, Age: 25
You can also work with JSON arrays, which are a common structure in JSON data. Let’s see how to handle an array of objects:
using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 }
};
string jsonString = JsonSerializer.Serialize(people);
Console.WriteLine(jsonString);
}
}
[{"Name":"Alice","Age":30},{"Name":"Bob","Age":25}]
You might need to manipulate JSON data directly. The JsonDocument
class allows you to parse and navigate through JSON data without deserializing it into a specific object type.
using System;
using System.Text.Json;
class Program
{
static void Main()
{
string jsonString = "{"Name":"Charlie","Age":40}";
using (JsonDocument doc = JsonDocument.Parse(jsonString))
{
JsonElement root = doc.RootElement;
string name = root.GetProperty("Name").GetString();
int age = root.GetProperty("Age").GetInt32();
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
}
Name: Charlie, Age: 40
Working with JSON data in C# is straightforward with the System.Text.Json
library. By understanding how to serialize, deserialize, and manipulate JSON data, you can efficiently handle many data interchange scenarios in your applications.