C# 使用 HttpClient 获取 JSON 数据并反序列化
以下是 C# 访问 URL 获取 JSON 数据并进行反序列化的代码示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ConsoleApp
{
class Program
{
static async Task Main(string[] args)
{
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync('https://jsonplaceholder.typicode.com/posts/1');
var json = await response.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<Post>(json);
Console.WriteLine('ID: ' + post.Id);
Console.WriteLine('Title: ' + post.Title);
Console.WriteLine('Body: ' + post.Body);
}
}
}
class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
在此示例中,我们使用 HttpClient 类访问 URL 以获取 JSON 数据。然后,我们使用 JsonConvert 类中的 DeserializeObject 方法将 JSON 数据反序列化为 Post 类的实例。最后,我们将反序列化后的数据输出到控制台。请注意,我们必须先定义一个 Post 类,以便 JsonConvert 类知道要将 JSON 数据反序列化为哪种类型的实例。
原文地址: https://www.cveoy.top/t/topic/oiy9 著作权归作者所有。请勿转载和采集!