以下是使用 C# 访问 URL 获取 JSON 数据并进行反序列化的示例:

using System;
using System.Net;
using System.IO;
using System.Text.Json;

// 定义一个类来存储 JSON 数据的属性
public class MyData
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    
    {
        string url = 'https://example.com/data.json'; // 替换为你的 URL

        // 创建一个 Web 客户端并获取 JSON 数据
        WebClient webClient = new WebClient();
        string jsonData = webClient.DownloadString(url);

        // 将 JSON 数据反序列化为 MyData 对象
        MyData data = JsonSerializer.Deserialize<MyData>(jsonData);

        // 输出数据
        Console.WriteLine($'Name: {data.Name}');
        Console.WriteLine($'Age: {data.Age}');
    }
}

在上面的示例中,我们使用了 .NET 的内置 WebClient 类来访问 URL 并获取 JSON 数据。然后,我们使用 .NET Core 3.0 引入的 System.Text.Json 命名空间中的 JsonSerializer.Deserialize<T>() 方法将 JSON 数据反序列化为 MyData 对象。最后,我们输出了反序列化后的数据。

C# 访问 URL 获取 JSON 数据并反序列化 - 示例教程

原文地址: https://www.cveoy.top/t/topic/oizK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录