Appearance
存储和检索 JSON 文件
System.Text.Json 命名空间
System.Text.Json 命名空间是 .NET 中用于处理 JSON 数据的强大库。 它为序列化(将 C# 对象转换为 JSON)和反序列化(将 JSON 转换回 C# 对象)提供功能。 该库设计为快速、高效且易于使用,使其成为在 C# 应用程序中使用 JSON 的开发人员的热门选择。
该 System.Text.Json 库是 .NET Core 框架的一部分,包含在 .NET 5 及更高版本中。 它提供了一组用于处理 JSON 数据的类和方法,包括:
JsonSerializer:用于将 C# 对象转换为 JSON 的类,反之亦然。 它提供序列化和反序列化 JSON 数据的方法,以及用于自定义序列化过程的选项。JsonDocument:用于读取和分析 JSON 数据的类。 它允许开发人员导航和查询 JSON 结构,而无需将其反序列化为 C# 对象。JsonElement:表示 JSON 值的结构。 它提供访问和作 JSON 数据的方法,使开发人员能够以更灵活的方式使用 JSON 结构。
该 JsonSerializer 类是用于 System.Text.Json 命名空间中的序列化和反序列化的主要类。 它提供将 C# 对象转换为 JSON 字符串的方法,反之亦然,因此可以轻松地在 C# 应用程序中处理 JSON 数据。
JsonSerializer
该 JsonSerializer 类提供以下方法来序列化和反序列化 JSON:
Serialize:将 C# 对象转换为 JSON 字符串。Deserialize:将 JSON 字符串转换回 C# 对象。
使用 JsonSerializer.Serialize 将对象序列化为 JSON
以下代码演示如何使用 JsonSerializer.Serialize 以下命令将对象转换为 JSON 字符串:
c#
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
class Program
{
static void Main()
{
var customer = new Employee { Name = "Anette Thomsen", Age = 30, Address = "123 Main St" };
string jsonString = JsonSerializer.Serialize(customer);
Console.WriteLine(jsonString);
}
}
// Output: {"Name":"Anette Thomsen","Age":30,"Address":"123 Main St"}使用 JsonSerializer.Deserialize 将 JSON 反序列化为对象
以下代码演示如何使用 JsonSerializer.Deserialize 以下命令将 JSON 字符串转换回对象:
c#
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Employee
{
public string Name { get; set; } = "Anette Thomsen";
public int Age { get; set; }
public string Address { get; set; } = "123 Main St";
}
class Program
{
static void Main()
{
string jsonString1 = "{\"Name\":\"Anette Thomsen\",\"Age\":30,\"Address\":\"123 Main St\"}";
string jsonString2 = @"{""Name"":""Anette Thomsen"",""Age"":30,""Address"":""123 Main St""}";
var customer = JsonSerializer.Deserialize<Employee>(jsonString2);
if (customer != null)
{
Console.WriteLine($"Name: {customer.Name}, Age: {customer.Age}, Address: {customer.Address}");
}
else
{
Console.WriteLine("Deserialization failed.");
}
}
}
// Output: Name: Anette Thomsen, Age: 30, Address: 123 Main St