Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# deserializes json with multiple arrays

I am trying to deserialize the following JSON file into 3 variables:
manager(Class)
Servers(list-class)
Admins(List-Class)

Everything I’ve tried so far doesn’t work. How should I do that?

{
   "Manager":{
      "ServerIp":"ServerIP",
      "ServerPort":"6000"
   },
   "Admins":[
      {
         "Name":"AdminUserName",
         "ID":"AdminID"
      }
   ]
   "Servers":[
      {
         "ServerName":"servername",
         "Path":"executablepath",
         "IP":"ip",
         "Port":"port",
         "Password":"pass"
      }
   ]
}
public class Manager
{
    public string? ServerIp { get; set; }
    public  string? ServerPort { get; set; }
}
public class Admins
{
    public string? Name { get; set; }
    public string? ID { get; set; }
}

public class Servers
{
    public string? ServerName { get; set; }
    public string? Path { get; set; }
    public string? IP { get; set; }
    public string? Port { get; set; }
    public string? Password { get; set; }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add another class that precisely matches the structure of the JSON that you’re describing:

public class Info // come up with a better name than "Info"...
{
   public Manager Manager { get; set; }
   public List<Admins> Admins { get; set; }
   public List<Servers> Servers { get; set; }
}

Then just deserialize the contents of this file into an instance of this class, for example (using System.Text.Json):

var json = File.ReadAllText(pathToFile);
var info = JsonSerializer.Deserialize<Info>(json);

Then just read the properties of info as you need them (Manager, etc.).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading