Home > Enterprise >  C# deserializes json with multiple arrays
C# deserializes json with multiple arrays

Time:09-09

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

CodePudding user response:

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.).

CodePudding user response:

here is an equivalent JSON model to your desired C# types. Nullable types are not recommended to use while working with JSON to C# Models. enter image description here

  • Related