1

所以我在做一个HttpWebRequest返回 jsonstring 的方法。反序列化的字符串如下所示:

{
    "have_warnings": "20",
    "pp_active": false,
    "noofslots": 2,
    "paused": true,
    "pause_int": "0",
    "mbleft": 7071.03378,
    "diskspace2": 55.610168,
    "diskspace1": 55.610168,
    "jobs": [{
        "timeleft": "0:00:00",
        "mb": 6918.785553,
        "msgid": "",
        "filename": "xxxx",
        "mbleft": 5869.015694,
        "id": "xx"
    },
    {
        "timeleft": "0:00:00",
        "mb": 2238.526516,
        "msgid": "",
        "filename": "xxxx",
        "mbleft": 1202.018086,
        "id": "xxxx"
    }],
    "speed": "0 ",
    "timeleft": "0:00:00",
    "mb": 9157.312069,
    "state": "Paused",
    "loadavg": "0.11 | 0.08 | 0.08 | V=444M R=88M",
    "kbpersec": 0.0
}

现在我想在我的 UI 的标签中显示一些数据。最好的方法是什么?

我试过了:

dynamic array = JsonConvert.DeserializeObject(qstatusOutput);

        foreach (var item in array) 
        {
            MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
        }

但我得到一个错误

“Newtonsoft.Json.Linq.JProperty”不包含“timeleft”的定义

4

3 回答 3

3

要采取类型安全的方法,您可以使用此站点:http: //json2csharp.com/

var root = JsonConvert.DeserializeObject<RootObject>(qstatusOutput);
foreach (var job in root.jobs)
{
    Console.WriteLine(job.timeleft);
}

public class Job
{
    public string timeleft { get; set; }
    public double mb { get; set; }
    public string msgid { get; set; }
    public string filename { get; set; }
    public double mbleft { get; set; }
    public string id { get; set; }
}

public class RootObject
{
    public string have_warnings { get; set; }
    public bool pp_active { get; set; }
    public int noofslots { get; set; }
    public bool paused { get; set; }
    public string pause_int { get; set; }
    public double mbleft { get; set; }
    public double diskspace2 { get; set; }
    public double diskspace1 { get; set; }
    public List<Job> jobs { get; set; }
    public string speed { get; set; }
    public string timeleft { get; set; }
    public double mb { get; set; }
    public string state { get; set; }
    public string loadavg { get; set; }
    public double kbpersec { get; set; }
}

但是如果你想使用dynamic那么

dynamic array = JsonConvert.DeserializeObject(qstatusOutput);

foreach (var item in array.jobs)
{
    MessageBox.Show(String.Format("{0} {1}", item.timeleft, item.mbleft));
}
于 2013-05-26T16:20:23.597 回答
0

剩下的时间在工作里面,所以试试下面

foreach (var item in array.jobs) 
{
   MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
}
于 2013-05-26T16:18:04.710 回答
0

您的结果DeserializeObject不是数组。它是一个包含数组作为一个属性的结构。

dynamic result = JsonConvert.DeserializeObject(qstatusOutput);
dynamic array = result.jobs;

foreach (var item in array) 
{
  MessageBox.Show("{0}{1}", item.timeleft, item.mbleft);
}
于 2013-05-26T16:19:54.093 回答