在.NET 8中,处理API和JSON交互变得更加简单和高效。首先,你需要创建一个HttpClient实例来发送HTTP请求。假设我们有一个简单的API,它返回用户数据的JSON对象,我们可以通过HttpClient的GetAsync方法来获取数据。接着,我们使用System.Text.Json命名空间下的JsonSerializer来反序列化JSON字符串,将其转换为C#对象。
我们可以创建一个User类来表示用户数据:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
接下来,使用HttpClient获取数据并解析:
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.example.com/users/1");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
User user = JsonSerializer.Deserialize<User>(responseBody);
Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}");
}
}
在这个例子中,我们首先发送HTTP GET请求来获取用户数据。确保请求成功后,读取响应内容,并将其反序列化为User对象。然后,我们可以方便地访问和使用这些数据。
如果你需要发送带有JSON数据的POST请求,你可以这样做:
using System.Text;
using System.Net.Http.Headers;
User newUser = new User { Id = 2, Name = "Jane Doe", Email = "jane.doe@example.com" };
string json = JsonSerializer.Serialize(newUser);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage postResponse = await client.PostAsync("https://api.example.com/users", content);
postResponse.EnsureSuccessStatusCode();