欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# .NET 遍历Json 形成键值对

程序员文章站 2022-03-04 13:33:15
...

原JSON字符串

{
	"errcode": 0,
	"result": [{
		"check_type": "OnDuty",
		"group_id": 532670037,
		"id": 142209165801,
		"is_rest": "N",
		"plan_check_time": "2020-09-04 07:50:00",
		"shift_id": 534475050,
		"shift_version": 510842386,
		"userid": "012524601729258924",
		"work_date": "2020-09-04 00:00:00"
	}, {
		"check_type": "OffDuty",
		"group_id": 532670037,
		"id": 142209165802,
		"is_rest": "N",
		"plan_check_time": "2020-09-04 12:00:00",
		"shift_id": 534475050,
		"shift_version": 510842386,
		"userid": "012524601729258924",
		"work_date": "2020-09-04 00:00:00"
	}, {
		"check_type": "OffDuty",
		"group_id": 532670037,
		"id": 142209165276,
		"is_rest": "N",
		"plan_check_time": "2020-09-04 18:00:00",
		"shift_id": 534475050,
		"shift_version": 510842386,
		"userid": "2410456929267501",
		"work_date": "2020-09-04 00:00:00"
	}],
	"success": true,
	"request_id": "roz8ezomhjsz"
}

遍历JSON

    var o = JObject.Parse(sch);

                    foreach (JToken child in o.Children())
                    {
                        //var property1 = child as JProperty;
                        //MessageBox.Show(property1.Name + ":" + property1.Value);
                        foreach (JToken grandChild in child)
                        {
                            //var property = grandChild as ResultInfo01;
                            //property.check_type;
                            JObject jo2 = (JObject)JsonConvert.DeserializeObject(grandChild.ToString());//转换为json对象
                            string userid = jo1["userid"].ToString();//获取值
                            string is_rest = jo1["is_rest"].ToString();//获取值
                            string work_date = jo1["work_date"].ToString();//获取值
                        }
                    }

三级

var o = JObject.Parse(yourJsonString);
 
            foreach (JToken child in o.Children())
            {
                //var property1 = child as JProperty;
                //MessageBox.Show(property1.Name + ":" + property1.Value);
                foreach (JToken grandChild in child)
                {
                    foreach (JToken grandGrandChild in grandChild)
                    {
                        var property = grandGrandChild as JProperty;
                        if (property != null)
                        {
                            MessageBox.Show(property.Name + ":" + property.Value);
                        }
                    }
                }
            }

 

相关标签: asp.net JSON