C#使用JObject解析JSON
C#中很难直接操作JsonResult类型,也没有提供更好的方法。 解决方案:序列化成Json字符串,再转换为JObject类型。
操作return Json(result);先序列化成Json字符串,再转换为JObject类型
1 ActionResult ar= em.Reject(morder.ToString(), remark, Duser, "DINGDING", taskresult); //return Json(result); 2 var jsonAR = Newtonsoft.Json.JsonConvert.SerializeObject(ar); 3 JObject jo = JObject.Parse(jsonAR);//将Json字符串转为JObject类型,后续可方便直接取值 4 var ARData = jo["Data"]; 5 var ARDataErrors = jo["Data"]["Errors"][0].ToString();
操作Json
static void Main(string[] args) { string strJson = "{\"Name\" : \"Ben\", \"Age\" : 30, \"education\" : [{\"School\" : \"university\" , \"year\":4},{\"School\" : \"highschool\" , \"year\":4}] }"; JObject jObject = JObject.Parse(strJson); string userName = (string)jObject["Name"]; Console.WriteLine(userName);//CPU JArray jsonColleagues = (JArray)jObject["education"]; Console.WriteLine(jsonColleagues.Count()); Console.WriteLine(jsonColleagues.Count); Console.WriteLine((string)((JArray)jObject["education"])[0]["School"]); Console.WriteLine((string)jsonColleagues[0]["School"]); Console.WriteLine((string)jsonColleagues[0]["year"]); Console.ReadLine(); ; }