2013-05-26 153 views
1

所以我即将做一个HttpWebRequest它返回一个jsonstring。反序列化的字符串看起来是这样的:阅读json字符串的内容

{ 
    "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中的标签显示的一些数据。什么是最好的方法来做到这一点?

我tryed:

dynamic array = JsonConvert.DeserializeObject(qstatusOutput); 

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

但我得到一个错误

'Newtonsoft.Json.Linq.JProperty' 不包含一个定义 '的timeleft'

回答

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)); 
} 
+0

+1谢谢你的网站。 – Nasreddine

+0

啊,有我的错误..现在它的工作:)真棒网站btw! 谢谢! –

0

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

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

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

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

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