【问题标题】:C# class with JSON file [duplicate]带有 JSON 文件的 C# 类 [重复]
【发布时间】:2020-10-29 03:26:00
【问题描述】:

我是 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"
        }
    ]
}

我希望在启动资源时,首先从站点检查是否有将其分配为变量的服务器名称,如果存在,则必须仅从该服务器打印所有数据,例如,如果有是Name 1 我只得到Name 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();
    }
}

我需要一门课程以及如何使用它的说明。谢谢

【问题讨论】:

  • 这个json文件是你制作的吗?
  • 是的,错了吗?我以一个文件为例,但我修改了它
  • 没有错,但我不认为你的 Name 1Name 2 实际上是数组。此外,您可能不想在对象名称中添加空格。即Name 1 应该是Name_1Name1。名称中的空格可能会导致问题。
  • 键是否总是名称 1 和名称 2?
  • 我建议您查看 JSON 文件结构。这是一个很好的资源w3schools.com/js/js_json_intro.asp

标签: c# arrays json class


【解决方案1】:

您可能希望使用JsonSerializer.Deserialize 方法(更多信息请参见these docs)。这将允许您从 Json 文件创建 C# 对象。

首先你要定义一个类,像这样:

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; }
    }

并通过传入该数据字符串来创建您的对象:

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

然后您可以使用该对象来分析/打印信息。

【讨论】:

  • 没用。此外,我的站点上不会总是有两台服务器,但每次我都会添加一台。我希望每次允许一个人启动资源时,我只需将其添加到站点而不更改资源。
  • @FabioPaombi 什么不起作用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 2016-03-30
  • 2019-08-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多