Reputation: 54
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!
Upvotes: 1
Views: 137
Reputation: 1610
Your ServerCollection
class does not implement the IEnumerable
interface. You have two options:
ServerCollection
implement that interface (i.e., public class ServerCollection : IEnumerable<Server>
and add the necessary methods)_servers.servers
insteadThe second option is the easier one to get you going, but implementing the interface may have other benefits down the road
Upvotes: 0
Reputation: 7091
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
}
Upvotes: 1