跳到主要内容

C# JSON 处理

介绍

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于 Web 应用程序和 API 中。C# 提供了强大的工具来处理 JSON 数据,包括序列化(将对象转换为 JSON 字符串)和反序列化(将 JSON 字符串转换为对象)。本文将逐步介绍如何在 C# 中处理 JSON 数据。

1. 安装 JSON 库

在 C# 中处理 JSON 数据通常使用 System.Text.JsonNewtonsoft.Json 库。System.Text.Json 是 .NET Core 3.0 及更高版本中的内置库,而 Newtonsoft.Json 是一个流行的第三方库。

如果你使用的是 .NET Core 3.0 或更高版本,可以直接使用 System.Text.Json。否则,可以通过 NuGet 安装 Newtonsoft.Json

bash
dotnet add package Newtonsoft.Json

2. 序列化对象为 JSON

序列化是将 C# 对象转换为 JSON 字符串的过程。以下是一个简单的示例:

csharp
using System;
using System.Text.Json;

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

class Program
{
static void Main()
{
var person = new Person { Name = "Alice", Age = 30 };
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
}
}

输出:

json
{"Name":"Alice","Age":30}
备注

JsonSerializer.Serialize 方法将对象转换为 JSON 字符串。默认情况下,它会生成紧凑的 JSON 格式。你可以通过传递 JsonSerializerOptions 参数来格式化输出。

3. 反序列化 JSON 为对象

反序列化是将 JSON 字符串转换回 C# 对象的过程。以下是一个示例:

csharp
using System;
using System.Text.Json;

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

class Program
{
static void Main()
{
string jsonString = "{\"Name\":\"Alice\",\"Age\":30}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}

输出:

plaintext
Name: Alice, Age: 30
提示

JsonSerializer.Deserialize 方法将 JSON 字符串转换回指定类型的对象。确保 JSON 字符串的结构与目标类的属性匹配。

4. 处理复杂 JSON 数据

在实际应用中,JSON 数据可能包含嵌套对象或数组。以下是一个处理复杂 JSON 数据的示例:

csharp
using System;
using System.Text.Json;

public class Address
{
public string City { get; set; }
public string Country { get; set; }
}

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}

class Program
{
static void Main()
{
string jsonString = "{\"Name\":\"Alice\",\"Age\":30,\"Address\":{\"City\":\"New York\",\"Country\":\"USA\"}}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.Address.City}, Country: {person.Address.Country}");
}
}

输出:

plaintext
Name: Alice, Age: 30, City: New York, Country: USA
警告

处理嵌套对象时,确保 JSON 字符串的结构与目标类的嵌套结构完全匹配,否则反序列化可能会失败。

5. 实际应用场景

JSON 处理在 Web API 开发中非常常见。例如,当你从 API 获取数据时,通常会收到 JSON 格式的响应。你可以使用 C# 将这些 JSON 数据反序列化为对象,以便在应用程序中使用。

以下是一个从 API 获取 JSON 数据并反序列化的示例:

csharp
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

public class Post
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}

class Program
{
static async Task Main()
{
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts/1");
Post post = JsonSerializer.Deserialize<Post>(response);
Console.WriteLine($"Title: {post.Title}\nBody: {post.Body}");
}
}

输出:

plaintext
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body: quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto
注意

在实际应用中,处理网络请求时要注意异常处理,例如网络错误或无效的 JSON 数据。

6. 总结

在本文中,我们学习了如何在 C# 中处理 JSON 数据,包括序列化和反序列化操作。我们还探讨了如何处理复杂的 JSON 数据,并展示了在实际应用中的使用场景。

7. 附加资源与练习

  • 练习 1: 创建一个包含多个嵌套对象的类,并尝试将其序列化为 JSON 字符串。
  • 练习 2: 从公共 API 获取 JSON 数据,并将其反序列化为 C# 对象。
  • 资源: System.Text.Json 官方文档

通过不断练习和探索,你将能够熟练地在 C# 中处理 JSON 数据,为开发更复杂的应用程序打下坚实的基础。