c# - 带有 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();
}
}
请我需要一堂课并解释如何使用它。谢谢
解决方案
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.
推荐阅读
- reactjs - 无法使用 kubernetes 连接到 react js 应用程序的 api 服务器?
- node.js - 最新版本的mongo db连接器可以与loopback@2.26.2一起使用吗
- c# - 如何使用 ConfigurationManager.AppSettings?
- excel - 如何在我的列表框中显示来自另一个工作表的数据?
- swift - Why is the leading swipe action also duplicated as a trailing action?
- python - 错误:OpenCV(4.1.0) 错误:(-215:Assertion failed) !ssize.empty() in function 'cv::resize'
- .net - 在不可靠的网络环境中发布 ClickOnce Winforms 应用程序
- go - 为 Go 程序构建最小容器
- reactjs - 使用 React 路由器的站点中的 Slash 问题
- laravel - 如何填写邮件验证字段?