在c#中遍历json对象

本文关键字:json 对象 遍历 | 更新日期: 2023-09-27 18:28:16

我想创建一个循环来检查Json对象的条件。我正在寻找一种迭代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
}

我知道如何映射它,所以让我们假设我映射任务和根对象如下:

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);

然后使用任务检查它的所有属性

如何检查所有任务?

提前感谢!

在c#中遍历json对象

如果您想遍历所有任务,可以使用:

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

或者你可以使用LINQ来过滤它们,比如这样的:

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

这和您的示例基本相同,只是Where返回IEnumerable,而不是像您的示例中的FirstOrDefault那样返回Task。

在json.net 中使用JArray和JObject

这里有一些非常好的样品

http://james.newtonking.com/projects/json/help/index.html?topic=html/QueryingLINQtoJSON.htm

http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_Linq_JArray.htm