2013-08-20 191 views
3

我想創建一個循環來檢查我的Json對象上的條件。我正在尋找一種方式,通過我的JSON對象進行迭代:在c中通過json對象迭代#

JSON:

{"tasks":[ 
     { 
      "id":-1, 
      "name":"Gantt editor", 
      "code":"", 
      "level":0, 
      "status":"STATUS_ACTIVE", 
      "start":1372608000000, 
      "duration":21, 
      "end":1375113599999, 
      "startIsMilestone":true, 
      "endIsMilestone":false, 
      "collapsed":false, 
      "assigs":[] 
     }, 
     { 
      "id":"tmp_fk1372575559620", 
      "name":"release", 
      "code":"", 
      "level":1, 
      "status":"STATUS_ACTIVE", 
      "start":1372608000000, 
      "duration":1, 
      "end":1372694399999, 
      "startIsMilestone":false, 
      "endIsMilestone":false, 
      "collapsed":false, 
      "assigs":[] 
     } 
     ],  // number of tasks may vary 
"selectedRow":8, 
"deletedTaskIds":[], 
"resources": 
    [ 
     { 
     "id":"tmp_1", 
     "name":"Resource 1" 
     } 
    ], 
"roles":[ 
     { 
      "id":"tmp_1", 
      "name":"Project Manager" 
     } 
     ], 
"canWrite":true, 
"canWriteOnParent":true 
} 

我知道如何映射它讓我們假設我映射任務和RootObject如下:

public class Task 
{ 
    public object id { get; set; } 
    public string name { get; set; } 
    public string code { get; set; } 
    public int level { get; set; } 
    public string status { get; set; } 
    public object start { get; set; } 
    public int duration { get; set; } 
    public object end { get; set; } 
    public bool startIsMilestone { get; set; } 
    public bool endIsMilestone { get; set; } 
    public bool collapsed { get; set; } 
    public List<object> assigs { get; set; } 
} 
public class RootObject 
{ 
    public List<Task> tasks { get; set; } 
    public int selectedRow { get; set; } 
    public List<object> deletedTaskIds { get; set; } 
    public List<Resource> resources { get; set; } 
    public List<Role> roles { get; set; } 
    public bool canWrite { get; set; } 
    public bool canWriteOnParent { get; set; } 
} // And etc ..... 

我知道如何手動檢查任務,例如用於第一個

Rootobject project = JsonConvert.DeserializeObject<Rootobject>(jsonString); 
    Task task = project.tasks.FirstOrDefault(t => t.id == "-1"); 
    decimal start = Convert.ToDecimal(task.start); 
    decimal end = Convert.ToDecimal(task.end); 
    decimal prog = Convert.ToDecimal(task.progress); 

,然後用任務來檢查所有的i t的屬性

如何檢查所有任務?

在此先感謝!

+1

'foreach(project.tasks中的var任務)'? – I4V

回答

3

如果你想通過所有任務迭代,你可以使用:

foreach (var task in project.tasks) 
{ 
    // do some stuff 
} 

或者你可以使用LINQ對其進行過濾,像這樣:

foreach (var task in project.tasks.Where(t => t.id == "-1")) 
{ 
    // do some stuff 
} 

這基本上是你的榜樣一樣,與凡在你的榜樣返回IEnumerable的不只是任務一樣FirstOrDefault唯一的區別。