我正在构建一个服务器仪表板应用程序。我想从每个服务器获取磁盘列表,并创建一个显示每个磁盘使用情况值的列表。
这是我们返回的 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,但我稍后会对此进行讨论。
提前谢谢。
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;
}
可能有更好的方法可以执行此操作,但使用提供的 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"]
});
}