在C#中调用Web API并根据JSON响应生成实体结果,涉及以下几个步骤:
1. 定义实体类
比如我们定义一个User
类
1public class User
2{
3 public int Id { get; set; }
4 public string FirstName { get; set; }
5 public string LastName { get; set; }
6 public string Email { get; set; }
7}
2. 发起HTTP请求并解析JSON
接下来,使用HttpClient
类来发起HTTP GET请求到Web API,并使用JsonSerializer
或第三方库如Newtonsoft.Json来反序列化JSON响应为C#对象。 (基于.NET Core 3.0+ 以上)
1using System;
2using System.Net.Http;
3using System.Text.Json;
4using System.Threading.Tasks;
5
6class Program
7{
8 static async Task Main(string[] args)
9 {
10 using var httpClient = new HttpClient();
11 var response = await httpClient.GetAsync("https://api.example.com/users/1");
12 response.EnsureSuccessStatusCode();
13
14 var json = await response.Content.ReadAsStringAsync();
15 var user = JsonSerializer.Deserialize<User>(json);
16
17 Console.WriteLine($"User: {user.FirstName} {user.LastName}");
18 }
19}
使用Newtonsoft.Json
如果你的项目中使用了Newtonsoft.Json,那么可以这样做:
1using System;
2using System.Net.Http;
3using Newtonsoft.Json;
4using System.Threading.Tasks;
5
6class Program
7{
8 static async Task Main(string[] args)
9 {
10 using var httpClient = new HttpClient();
11 var response = await httpClient.GetAsync("https://api.example.com/users/1");
12 response.EnsureSuccessStatusCode();
13
14 var json = await response.Content.ReadAsStringAsync();
15 var user = JsonConvert.DeserializeObject<User>(json);
16
17 Console.WriteLine($"User: {user.FirstName} {user.LastName}");
18 }
19}