C#遍历对象列表

时间:2020-02-17 18:42:00

标签: c# json.net

第一篇文章在这里,让我轻松一点!

我正在尝试将json文档反序列化为对象列表。

到目前为止,我有两个类-一个包含数据结构:

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

}

包含集合的另一个

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

在应用程序中,我执行了一个简单的ReadAllText,然后像这样反序列化对象

    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

我正在努力使用foreach对此进行迭代。。。我想不到我所缺少的东西。

appcfg.py -A your-project-name download_app folder-where-to-download

对我错过的事情有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

}

不是集合,但是Servers是,您需要对其进行迭代。

foreach (var server in _servers.servers)
{
    //do something with  server
}

答案 1 :(得分:0)

您的ServerCollection类未实现IEnumerable接口。您有两种选择:

  1. ServerCollection实现了该接口(即public class ServerCollection : IEnumerable<Server>并添加了必要的方法)
  2. 改为代替_servers.servers

第二种选择是更容易上手的选择,但是实施该接口可能会带来其他好处

相关问题