1

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; }
}
2
  • 2
    Well, look at your json. What is the root object? It's a json object with three properties. Just create a model class that precisely reflects this root json object with its three properties (including the correct types appropriate for the kind of values these properties have) and deserialize your json to that model class. Commented Sep 8, 2022 at 13:17
  • This is not valid JSON Commented Sep 8, 2022 at 13:30

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. Unfortunately I get the following exception with this code: Newtonsoft.Json.JsonReaderException: "After parsing a value an unexpected character was encountered: ". Path 'Admins', line 12, position 3."
@Toni Because your JSON is invalid and is missing a comma
@Toni specifically missing ',' after "Admins": [...]".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.