1

First post on here so go easy on me!

I'm trying to deserialize a json document into a list of objects.

So far I've got two classes - one which contains the data structure:

 class Server
{
    public string hostname { get; set; }
    public string ipAddress { get; set; }
    public string monitoring { get; set; }
    public int pollingInterval { get; set; }

}

The other that contains the collection

    class ServerCollection 
{
    public List<Server> servers { get; set; }

}

In the applicaion I do a simple ReadAllText and I'm deserializing the object like so

private ServerCollection _servers;
string json = File.ReadAllText(@"c:\users\admin\desktop\server.monitoring\servers.json");
_servers = JsonConvert.DeserializeObject<ServerCollection>(json);

I'm struggling to iterate over this using a foreach... Can't think what I'm missing.

    Severity    Code    Description Project File    Line    Suppression State
Error   CS1579  foreach statement cannot operate on variables of type 'ServerCollection' because 'ServerCollection' does not contain a public instance definition for 'GetEnumerator'   Server.Monitoring.Service.Core  C:\Code\Admin\Server.Monitoring\Server.Monitoring.Service.Core\GetSystemHealth.cs   25  Active

Any ideas on what I've missed?

Thanks in advance!

1
  • 1
    What does the code that has the foreach look like and what does the JSON look like? Commented Feb 17, 2020 at 18:44

2 Answers 2

1
class ServerCollection 
{
    public List<Server> servers { get; set; }

}

Is not a collection but Servers is, you need to iterate over that.

foreach (var server in _servers.servers)
{
    //do something with  server
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so simple! Just forgetting that last '.servers'
@Syngate you should mark this as the right answer ;)
0

Your ServerCollection class does not implement the IEnumerable interface. You have two options:

  1. Have ServerCollection implement that interface (i.e., public class ServerCollection : IEnumerable<Server> and add the necessary methods)
  2. Loop over _servers.servers instead

The second option is the easier one to get you going, but implementing the interface may have other benefits down the road

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.