2

我正在构建一个服务器仪表板应用程序。我想从每台服务器中获取磁盘列表并创建一个显示每个服务器使用值的列表。

这是我们要返回的 JSON 示例...

    {"server":"webster","disks":[ {"use": "91%", "used": "16G", "mount": "/", "free": "1.6G", "device": "/dev/mapper/vg_f12-lv_root", "total": "18G", "type": "ext4"} ,
{"use": "0%", "used": "0", "mount": "/dev/shm", "free": "500M", "device": "tmpfs", "total": "500M", "type": "tmpfs"} ,
{"use": "22%", "used": "40M", "mount": "/boot", "free": "145M", "device": "/dev/sda1", "total": "194M", "type": "ext4"} ,
{"use": "47%", "used": "52G", "mount": "/rsync", "free": "61G", "device": "/dev/sdb1", "total": "119G", "type": "ext3"} ]}

我用 C# 代码做到了这一点:

            WebClient c = new WebClient();
            var data = c.DownloadString("http://192.0.0.40:8000/cgi-bin/df.py");
            JObject o = JObject.Parse(data);
            string serv = o["server"].Select(s => (string)s).ToString();
            lblJson.Text = serv;

但是我似乎无法将“磁盘”提取到可以插入列表视图的任何有意义的东西中。我尝试将其注入 IList,但它总是崩溃或给我一些来自 Intellisense 的粗鲁评论。

我确实为此构建了一个类,但还没有弄清楚如何将信息移植到其中。作为参考,它在这里:

public class drive
    {
        public string Usage;
        public string usedSpace;
        public string Mount;
        public string freeSpace;
        public string Device;
        public string Total;
        public string Type;
    }

注意:JSON 的来源是 Linux 服务器。Windows 服务器最终将以不同的格式提供数据。

然后我们有 VMWare,但我稍后会继续讨论。

提前致谢。

4

2 回答 2

4
var jsonObj = JsonConvert.DeserializeObject<RootObject>(json);


public class RootObject
{
    [JsonProperty("server")]
    public string Server;
    [JsonProperty("disks")]
    public List<Drive> Disks;
}

public class Drive
{
    [JsonProperty("use")]
    public string Usage;
    [JsonProperty("used")]
    public string usedSpace;
    [JsonProperty("mount")]
    public string Mount;
    [JsonProperty("free")]
    public string freeSpace;
    [JsonProperty("device")]
    public string Device;
    [JsonProperty("total")]
    public string Total;
    [JsonProperty("type")]
    public string Type;
}
于 2012-11-26T19:31:56.343 回答
2

可能有更好的方法来做到这一点,但使用提供的drive类,以下工作可以反序列化您提供的 JSON:

JObject o = JObject.Parse(data);
List<drive> drives = new List<drive>();
string server = (string)o["server"];
foreach (var d in o["disks"].Children())
{
    drives.Add(new drive()
    {
        Usage = (string)d["use"],
        usedSpace = (string)d["used"],
        Mount = (string)d["mount"],
        freeSpace = (string)d["free"],
        Device = (string)d["device"],
        Total = (string)d["total"],
        Type = (string)d["type"]
    });
}
于 2012-11-26T19:30:01.040 回答