带有 JSON 文件的 C# 类 [重复]

Posted

技术标签:

【中文标题】带有 JSON 文件的 C# 类 [重复]【英文标题】:C# class with JSON file [duplicate] 【发布时间】: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 【参考方案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 什么不起作用?

以上是关于带有 JSON 文件的 C# 类 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

C#反序列化带有ID节点的Json [重复]

如何在 C# Unity 中加载带有扩展名(.json)的资产文件夹中的任何文件

获取json文件信息并使用它的最佳方法[重复]

在调用API后,将JSON对象反序列化为C#类[重复]。

如何将 XML/JSON 文件转换为 C# 类?

使用 C# 解析 JSON 文本文件