c#解析Josn(解析多个子集,数据,可解析无限级json)
首先引用 解析类库
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPMS.WEB.Common { public class CommonJsonModel : CommonJsonModelAnalyzer { private string rawjson; private bool isValue = false; private bool isModel = false; private bool isCollection = false; public CommonJsonModel(string rawjson) { this.rawjson = rawjson; if (string.IsNullOrEmpty(rawjson)) throw new Exception("missing rawjson"); rawjson = rawjson.Trim(); if (rawjson.StartsWith("{")) { isModel = true; } else if (rawjson.StartsWith("[")) { isCollection = true; } else { isValue = true; } } public string Rawjson { get { return rawjson; } } public bool IsValue() { return isValue; } public bool IsValue(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsValue(); } } return false; } public bool IsModel() { return isModel; } public bool IsModel(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsModel(); } } return false; } public bool IsCollection() { return isCollection; } public bool IsCollection(string key) { if (!isModel) return false; if (string.IsNullOrEmpty(key)) return false; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); return submodel.IsCollection(); } } return false; } /// <summary> /// 当模型是对象,返回拥有的key /// </summary> /// <returns></returns> public List<string> GetKeys() { if (!isModel) return null; List<string> list = new List<string>(); foreach (string subjson in base._GetCollection(this.rawjson)) { string key = new CommonJsonModel(subjson).Key; if (!string.IsNullOrEmpty(key)) list.Add(key); } return list; } /// <summary> /// 当模型是对象,key对应是值,则返回key对应的值 /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetValue(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key != key) continue; if (model.Key == key) return model.Value; } return null; } /// <summary> /// 模型是对象,key对应是对象,返回key对应的对象 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetModel(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsModel()) return null; else return submodel; } } return null; } /// <summary> /// 模型是对象,key对应是集合,返回集合 /// </summary> /// <param name="key"></param> /// <returns></returns> public CommonJsonModel GetCollection(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsCollection()) return null; else return submodel; } } return null; } /// <summary> /// 模型是集合,返回自身 /// </summary> /// <returns></returns> public List<CommonJsonModel> GetCollection() { List<CommonJsonModel> list = new List<CommonJsonModel>(); if (IsValue()) return list; foreach (string subjson in base._GetCollection(rawjson)) { list.Add(new CommonJsonModel(subjson)); } return list; } /// <summary> /// 当模型是值对象,返回key /// </summary> private string Key { get { if (IsValue()) return base._GetKey(rawjson); return null; } } /// <summary> /// 当模型是值对象,返回value /// </summary> private string Value { get { if (!IsValue()) return null; return base._GetValue(rawjson); } } } }
解析类父类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPMS.WEB.Common { public class CommonJsonModelAnalyzer { protected string _GetKey(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }); if (jsons.Length < 2) return rawjson; return jsons[0].Replace("\"", "").Trim(); } protected string _GetValue(string rawjson) { if (string.IsNullOrEmpty(rawjson)) return rawjson; rawjson = rawjson.Trim(); string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (jsons.Length < 2) return rawjson; StringBuilder builder = new StringBuilder(); for (int i = 1; i < jsons.Length; i++) { builder.Append(jsons[i]); builder.Append(":"); } if (builder.Length > 0) builder.Remove(builder.Length - 1, 1); string value = builder.ToString(); if (value.StartsWith("\"")) value = value.Substring(1); if (value.EndsWith("\"")) value = value.Substring(0, value.Length - 1); return value; } protected List<string> _GetCollection(string rawjson) { //[{},{}] List<string> list = new List<string>(); if (string.IsNullOrEmpty(rawjson)) return list; rawjson = rawjson.Trim(); StringBuilder builder = new StringBuilder(); int nestlevel = -1; int mnestlevel = -1; for (int i = 0; i < rawjson.Length; i++) { if (i == 0) continue; else if (i == rawjson.Length - 1) continue; char jsonchar = rawjson[i]; if (jsonchar == '{') { nestlevel++; } if (jsonchar == '}') { nestlevel--; } if (jsonchar == '[') { mnestlevel++; } if (jsonchar == ']') { mnestlevel--; } if (jsonchar == ',' && nestlevel == -1 && mnestlevel == -1) { list.Add(builder.ToString()); builder = new StringBuilder(); } else { builder.Append(jsonchar); } } if (builder.Length > 0) list.Add(builder.ToString()); return list; } } }
示例
这里 注意点 要传json数组进来
[{
"键": [ { } ],
"键": [{ } ]
}]
要替换掉json内所有空格 Replace(" ","") ,Replace(Json, @"\r\n", "")
如果 json 键值对 传进来的值中 含有 ',' 隔开的值 则 需用 其他符号 替代 否则 取值时 取不全!
public string ImportData(string Json) { StringBuilder sbStr = new StringBuilder(); CommonJsonModel model = new CommonJsonModel(Regex.Replace(Json, @"\r\n", "")); List<CommonJsonModel> lst = model.GetCollection(); foreach (CommonJsonModel item in lst) { #region string ImgList = item.GetValue("ImgList"); CommonJsonModel modelImgList = new CommonJsonModel(Regex.Replace(ImgList, @"\r\n", "")); List<CommonJsonModel> lstImgList = modelImgList.GetCollection(); List<string> sqlDelImgList = new List<string>(); List<string> sqlInserImgList = new List<string>(); foreach (CommonJsonModel itemImgList in lstImgList) { string ID = itemImgList.GetValue("ID");// if (ID != "0") { sqlDelImgList.Add(string.Format("DELETE FROM MR_Img WHERE AppID={0}",ID)); } string Img = itemImgList.GetValue("Img"); string Describe = itemImgList.GetValue("Describe"); string sqlInsertImg = string.Format("INSERT INTO MR_Img([FilePathe],[Small_FilePathe],[Describe],[AppID]) VALUES('{0}','{1}','{2}',{3})", Img, Img, Describe, ID); sqlInserImgList.Add(sqlInsertImg); } int ictDelImg = DBHelper.ExecuteSqlTran(sqlDelImgList); // int ictImg = DBHelper.ExecuteSqlTran(sqlInserImgList); #endregion #region string ExamineItem = item.GetValue("ExamineItem"); CommonJsonModel modelExamineItem = new CommonJsonModel(Regex.Replace(ExamineItem, @"\r\n", "")); List<CommonJsonModel> lstExamineItem = modelExamineItem.GetCollection(); List<string> sqlDelExamineItemList = new List<string>(); List<string> sqlInsExamineItemList = new List<string>(); foreach (CommonJsonModel itemExamineItem in lstExamineItem) { string ID = itemExamineItem.GetValue("ID"); if (ID != "0") { sqlDelExamineItemList.Add(string.Format("DELETE FROM MR_Check_Details where AppID={0}",ID)); } string ExamineID = itemExamineItem.GetValue("ExamineID"); string FloorList = itemExamineItem.GetValue("FloorList"); string Danger = itemExamineItem.GetValue("Danger"); string Imgs = itemExamineItem.GetValue("Imgs"); string NewImgs = ""; if (Imgs != "" || Imgs != "0") { string imgids = Imgs.Replace("&",","); string sqlQueryImgsID = string.Format("SELECT [ID] FROM MR_Img WHERE AppID IN({0})", imgids); DataTable dtImgsID = DBHelper.ExecuteDataTable(sqlQueryImgsID, CommandType.Text); if (dtImgsID != null && dtImgsID.Rows.Count > 0) { foreach (DataRow ImsIdRow in dtImgsID.Rows) { NewImgs = NewImgs + "," + ImsIdRow["ID"]; } } } string Item_ID = itemExamineItem.GetValue("Item_ID"); string Remarks = itemExamineItem.GetValue("Remarks"); string Refuse = itemExamineItem.GetValue("Refuse"); string RefuseName = itemExamineItem.GetValue("RefuseName"); string sqlInsCheck_Details = string.Format("INSERT INTO MR_Check_Details ([Item_ID],[Danger],[Complete_Time],[Imgs],[Remarks],[Refuse],[RefuseName],[ExamID],[FloorList],[AppID]) VALUES({0},{1},getdate(),'{2}','{3}',{4},'{5}',{6},'{7}',{8})", Item_ID, Danger, NewImgs.Trim(','), Remarks, Refuse, RefuseName, ExamineID, FloorList, ID); sqlInsExamineItemList.Add(sqlInsCheck_Details); } int ictdelExamineItemList = DBHelper.ExecuteSqlTran(sqlDelExamineItemList); int ictExamineItemList = DBHelper.ExecuteSqlTran(sqlInsExamineItemList); #endregion #region string BuildList = item.GetValue("BuildList"); CommonJsonModel modelBuildList = new CommonJsonModel(Regex.Replace(BuildList, @"\r\n", "")); List<CommonJsonModel> lstBuildList = modelBuildList.GetCollection(); List<string> sqlUpBuidList = new List<string>(); foreach (CommonJsonModel itemBuildList in lstBuildList) { string ID = itemBuildList.GetValue("ID"); string Name = itemBuildList.GetValue("Name"); string Contact = itemBuildList.GetValue("Contact"); string Mobile = itemBuildList.GetValue("Mobile"); string OwnerName = itemBuildList.GetValue("OwnerName"); string OwnerMobile = itemBuildList.GetValue("OwnerMobile"); string User_ID = itemBuildList.GetValue("User_ID"); string Doorplate = itemBuildList.GetValue("Doorplate"); string Address = itemBuildList.GetValue("Address"); string FloorNum = itemBuildList.GetValue("FloorNum"); string UpBuild = string.Format("UPDATE MR_Building SET [Name] ='{0}',[Contact] = '{1}',[Mobile] = '{2}',[OwnerName] = '{3}',[OwnerMobile] = '{4}',[User_ID] = {5},[Doorplate] = '{6}',[Address] ='{7}',[FloorNum] ={8} WHERE ID={9}", Name, Contact, Mobile, OwnerName, OwnerMobile, User_ID, Doorplate, Address, FloorNum, ID); sqlUpBuidList.Add(UpBuild); } int ictUpBuidList = DBHelper.ExecuteSqlTran(sqlUpBuidList); #endregion #region int ictBuildExamine = 0; string BuildExamine = item.GetValue("BuildExamine"); CommonJsonModel modelBuildExamine = new CommonJsonModel(Regex.Replace(BuildExamine, @"\r\n", "")); List<CommonJsonModel> lstBuildExamine = modelBuildExamine.GetCollection(); foreach (CommonJsonModel itemBuildExamine in lstBuildExamine) { string ID = itemBuildExamine.GetValue("ID"); string BID = itemBuildExamine.GetValue("BID"); string NewDanger = ""; string Danger = itemBuildExamine.GetValue("Danger"); if (Danger != "" || Danger != "0") { string DangerIds = Danger.Replace("&", ","); string sqlQBuidDanger = string.Format("SELECT ID FROM MR_Check_Details where AppID in ({0})", DangerIds); DataTable dtBuildDanger = DBHelper.ExecuteDataTable(sqlQBuidDanger, CommandType.Text); if (dtBuildDanger != null && dtBuildDanger.Rows.Count > 0) { foreach (DataRow BuildDangerRow in dtBuildDanger.Rows) { NewDanger = NewDanger + "," + BuildDangerRow["ID"]; } } } string RemarkType = itemBuildExamine.GetValue("RemarkType"); string Remark = itemBuildExamine.GetValue("Remark"); string Remark2 = itemBuildExamine.GetValue("Remark2"); string Complete_Time = itemBuildExamine.GetValue("Complete_Time"); string UserID = itemBuildExamine.GetValue("UserID"); ictBuildExamine += LxAddCheckBuild(BID, NewDanger.Trim(','), Remark, Remark2, Complete_Time, UserID); } #endregion #region string StreetList = item.GetValue("StreetList"); CommonJsonModel modelStreetList = new CommonJsonModel(Regex.Replace(StreetList, @"\r\n", "")); List<CommonJsonModel> lstStreetList = modelStreetList.GetCollection(); List<string> SqlUpSteetList = new List<string>(); foreach (CommonJsonModel itemStreetList in lstStreetList) { string ID = itemStreetList.GetValue("ID"); string Name = itemStreetList.GetValue("Name"); string Address = itemStreetList.GetValue("Address"); string Type = itemStreetList.GetValue("Type"); string Business = itemStreetList.GetValue("Business"); string Layer = itemStreetList.GetValue("Layer"); string Acreage = itemStreetList.GetValue("Acreage"); string Has_Business = itemStreetList.GetValue("Has_Business"); string Owner_Name = itemStreetList.GetValue("Owner_Name"); string Phone = itemStreetList.GetValue("Phone"); string Run_Name = itemStreetList.GetValue("Run_Name"); string Run_Phone = itemStreetList.GetValue("Run_Phone"); string Place_x = itemStreetList.GetValue("Place_x"); string place_y = itemStreetList.GetValue("place_y"); string UserID = itemStreetList.GetValue("UserID"); string Extinguisher_Num = itemStreetList.GetValue("Extinguisher_Num"); string Emergency_Num = itemStreetList.GetValue("Emergency_Num"); string Alertor_Num = itemStreetList.GetValue("Alertor_Num"); string UpSteet = string.Format("UPDATE MR_Street SET [Name] = '{0}',[Type] = {1},[Address] = '{2}',[Business] = '{3}' ,[Layer]='{4}',[Acreage] ={5},[Has_Business] ='{6}',[Owner_Name] = '{7}',[Phone] ='{8}',[Run_Name] = '{9}',[Run_Phone] = '{10}',[Place_x] = {11},[place_y] = '{12}',[UserID] = {13} WHERE Id={14}", Name, Type, Address, Business, Layer, Acreage, Has_Business, Owner_Name, Phone, Run_Name, Run_Phone, Place_x, place_y, UserID,ID); SqlUpSteetList.Add(UpSteet); string UpSteetDeal = string.Format("UPDATE MR_Street_Detail SET [Extinguisher_Num] = {0},[Emergency_Num] = {1} ,[Alertor_Num] ={2} WHERE SID={3}",Extinguisher_Num,Emergency_Num,Alertor_Num,ID); SqlUpSteetList.Add(UpSteetDeal); } int ictUpSteetList=DBHelper.ExecuteSqlTran(SqlUpSteetList); #endregion #region string StreetExamine = item.GetValue("StreetExamine"); CommonJsonModel modelStreetExamine = new CommonJsonModel(Regex.Replace(StreetExamine, @"\r\n", "")); List<CommonJsonModel> lstStreetExamine = modelStreetExamine.GetCollection(); int ictStreetExamine = 0; foreach (CommonJsonModel itemStreetExaminee in lstStreetExamine) { // string ID = itemStreetExaminee.GetValue("ID"); string SID = itemStreetExaminee.GetValue("SID"); string NewDanger = ""; string Danger = itemStreetExaminee.GetValue("Danger"); if (Danger != "" || Danger != "0") { string DangerIds = Danger.Replace("&", ","); string sqlQStreetDanger = string.Format("SELECT ID FROM MR_Check_Details where AppID in ({0})", DangerIds); DataTable dtStreetDanger = DBHelper.ExecuteDataTable(sqlQStreetDanger, CommandType.Text); if (dtStreetDanger != null && dtStreetDanger.Rows.Count > 0) { foreach (DataRow StreetDangerRow in dtStreetDanger.Rows) { NewDanger = NewDanger + "," + StreetDangerRow["ID"]; } } } string RemarkType = itemStreetExaminee.GetValue("RemarkType"); string Remark = itemStreetExaminee.GetValue("Remark"); string Remark2 = itemStreetExaminee.GetValue("Remark2"); string Complete_Time = itemStreetExaminee.GetValue("Complete_Time"); string UserID = itemStreetExaminee.GetValue("UserID"); ictStreetExamine+= LxAddCheckNew(SID, NewDanger.Trim(','), RemarkType, Remark, Remark2, Complete_Time, UserID); } #endregion } return ""; }