首先使用HttpClient发送请求并检查响应状态,再通过System.Text.Json反序列化JSON数据;需定义匹配的C#模型类,设置PropertyNameCaseInsensitive=true忽略大小写,并用try-catch处理解析异常,确保调用稳定性。
.NET 调用 RESTful API 并处理返回的 JSON 数据是现代开发中的常见
需求。你可以使用 HttpClient 类来发送 HTTP 请求,并结合 System.Text.Json 来反序列化 JSON 响应。下面是一个清晰、实用的调用与处理流程。
在 .NET 中,推荐使用 IHttpClientFactory 创建 HttpClient 实例,避免资源泄漏并提升性能。
示例:通过 HttpClient 获取数据代码片段:
using var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/users/1");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
// 接下来处理 JSON
}
else
{
Console.WriteLine($"请求失败: {response.StatusCode}");
}
为 API 返回的 JSON 结构创建对应的 C# 类,便于类型安全地访问数据。
示例:假设 API 返回如下 JSON{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
对应 C# 模型:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
将获取的 JSON 字符串反序列化为强类型对象。
完整处理示例:
using var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/users/1");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var user = JsonSerializer.Deserialize(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true // 忽略 JSON 字段大小写
});
Console.WriteLine($"用户: {user.Name}, 邮箱: {user.Email}");}
错误处理与健壮性建议
实际项目中需增强容错能力。
增强版调用示例:
try
{
var json = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(json))
throw new Exception("API 返回空内容");
var user = JsonSerializer.Deserialize(json, new JsonSerializerOptions
{ PropertyNameCaseInsensitive = true });
if (user == null)
throw new Exception("无法解析用户数据");
}
catch (JsonException ex)
{
Console.WriteLine("JSON 解析失败: " + ex.Message);
}
基本上就这些。合理封装 HttpClient 调用,配合模型类和 JSON 处理,就能稳定调用大多数 RESTful 接口。不复杂但容易忽略细节,比如大小写匹配和异常边界处理。