c#访问url获取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/fyJZ 著作权归作者所有。请勿转载和采集!