首页 > 解决方案 > 带有 JSON 文件的 C# 类

问题描述

我是 C# 新手,我不知道如何使用 json 文件。我希望我的脚本在我的网站上搜索 json 文件,但我不知道如何创建与该文件一起使用的类。这是我的 json 文件

{    
    "Name 1": [
        { 
            "license_on":true, 
            "webhook":"Discord Webhook",
            "serverName": "Server Name",
            "idDiscord": "Discord ID",
            "discordName": "Serse Dio Re",
            "ipAllowed": "IP allowed to use the script",
            "license": "License"
        }
    ],
    "Name 2": [
        { 
            "license_on":true, 
            "webhook":"Discord Webhook",
            "serverName": "Server Name",
            "idDiscord": "Discord ID",
            "discordName": "Serse Dio Re",
            "ipAllowed": "IP allowed to use the script",
            "license": "License"
        }
    ]
}

我希望在启动资源时,首先从站点检查是否有将其分配为变量的服务器的名称,如果存在,则必须仅从该服务器打印所有数据,例如是否有名称 1我只得到名字1的特征。这是我在c#中的初始代码

public static void ReadSite()
{
    try
    {
        string site = "My Site where json file";
        WebClient wc = new WebClient();
        string data = wc.DownloadString(site);

        // some code
    }
    catch(Exception e)
    {
        Console.WriteLine($"{e.Message}");
        Console.WriteLine($"{e.GetType()}");
        Console.ReadLine();
    }
}

请我需要一堂课并解释如何使用它。谢谢

标签: c#arraysjsonclass

解决方案


You'll probably want to use the JsonSerializer.Deserialize method (more info in these docs). This will let you create C# objects from a Json file.

First you'll want to define a class, something like this:

public class JsonDataClass
    {
        public Name[] Name1 { get; set; }
        public Name[] Name2 { get; set; }
    }

    public partial class Name
    {
        public bool LicenseOn { get; set; }
        public string Webhook { get; set; }
        public string ServerName { get; set; }
        public string IdDiscord { get; set; }
        public string DiscordName { get; set; }
        public string IpAllowed { get; set; }
        public string License { get; set; }
    }

And create your object by passing in that data string:

var jsonData = JsonSerializer.Deserialize<JsonDataClass>(data);

you can then use that object to analyse/print info.


推荐阅读