读取json字符串的内容

时间:2013-05-26 16:13:47

标签: c# json visual-studio-2012

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

{
    "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'

3 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分:0)

剩下的时间是在工作中,所以请尝试以下

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

答案 2 :(得分:0)

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

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

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