-3

I'm new on C# and I don't know how can I work with json file. I want that my script search on json file on my site but I don't know how can I create class that work with that file. This is my json file

{    
    "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"
        }
    ]
}

I want that when the resource is started, check from the site first if there is the name of the server that assigns it as a variable, if it exists it must print all the data only from that server, for example if there is Name 1 I only get the characteristics of the Name 1. This is my initial code in 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();
    }
}

Please I need a class and an explanation of how to work with it. Thank you

justin.m.chase
  • 13,061
  • 8
  • 52
  • 100

1 Answers1

0

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.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • Didn't work. Also, there won't always be two servers on my site, but each time I will add one. I would like every time I allow a person to start the resource, I just have to add it to the site without changing the resource. – Fabio Palombi Jul 08 '20 at 17:29
  • @FabioPalombi what doesn't work? – Luke Storry Jul 08 '20 at 18:27