c#解析Josn(解析多个子集,数据,可解析无限级json)

news/2023/6/10 23:38:09

首先引用 解析类库

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;elsereturn 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;elsereturn 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);}}}
}
View Code

 

  解析类父类

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;}}
}
View Code

 

 示例 

   这里 注意点  要传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){#regionstring 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 "";}

  

转载于:https://www.cnblogs.com/jiebo/p/4627196.html


https://dhexx.cn/news/show-17243.html

相关文章

mysql索引优化 - 多表关联查询优化

1 left joinEXPLAIN SELECT * FROM class LEFT JOIN book ON class.card book.card;LEFT JOIN条件用于确定如何从右表搜索行&#xff0c; 左边一定都有&#xff0c; #所以右边是我们的关键点&#xff0c;一定需要建立索引。结论&#xff1a;在优化关联查询时&#xff0c;只有在…

mysql索引优化 - 子查询优化

结论&#xff1a; 在范围判断时&#xff0c;尽量不要使用 not in 和 not exists&#xff0c;使用 left join on xxx is null 代替。 取所有不为掌门人的员工&#xff0c;按年龄分组&#xff01; select age as 年龄, count(*) as 人数 from t_emp where id not in (select ceo…

树莓派折腾---红外探测

先上个图&#xff1a; 用到的配件&#xff1a; 1.主角&#xff1a;树莓派 2.配角&#xff1a;红外探测 3.打杂&#xff1a;面包板&#xff0c;杜邦线&#xff0c;蜂鸣器&#xff0c;LED&#xff0c;电阻 红外探测有三个针脚&#xff0c;两端的是供电&#xff0c;中间是信号输出…

mysql索引优化 - 排序分组优化

where 条件和 on 的判断这些过滤条件&#xff0c;作为优先优化的部分&#xff0c;是要被先考虑的&#xff01; 其次&#xff0c;如果有分组和排序&#xff0c;那么 也要考虑 grouo by 和 order by。1. 必须有过滤&#xff0c;才会用到索引 结论&#xff1a;where&#xff0c;li…

UIView详解

来源&#xff1a;http://blog.csdn.net/chengyingzhilian/article/details/7894276 UIView表示屏幕上的一块矩形区域&#xff0c;它在App中占有绝对重要的地位&#xff0c;因为IOS中几乎所有可视化控件都是UIView的子类。负责渲染区域的内容&#xff0c;并且响应该区域内发生的…

jmeter基础入门(HTTP,TCP,SQL查询,新增,查看报告)

示例下载地址 https://download.csdn.net/download/qq_41712271/20398149有坑的地方 1 发送TCP请求&#xff0c;注意Tcp client classname,如下图&#xff0c;这里发送16进制&#xff0c;所以写 BinaryTCPClientImpl TCPClientImpl&#xff1a;纯文本为内容进行发送 BinaryT…

这么方便吗?用ChatGPT生成Excel(详解步骤)

文章目录前言使用过 ChatGPT 的人都知道&#xff0c;提示占据非常重要的位置。而 Word&#xff0c;Excel、PPT 这办公三大件中&#xff0c;当属 Excel 最难搞&#xff0c;想要熟练掌握它&#xff0c;需要记住很多公式。但是使用提示就简单多了&#xff0c;和 ChatGPT 聊聊天就能…

jenkins持续集成入门1

jenkins持续集成相关的软件安装分布架构图 软件安装的列表如下&#xff1a; jdk8或以上 maven git GitLab-EE Docker Harbor &#xff08;docker私服&#xff09; jenkins SonarQube &#xff08;代码审查&#xff09; Tomcat

HTML5新增Canvas标签及对应属性、API详解(基础一)

知识说明&#xff1a; HTML5新增的canvas标签&#xff0c;通过创建画布&#xff0c;在画布上创建任何想要的形状&#xff0c;下面将canvas的API以及属性做一个整理&#xff0c;并且附上时钟的示例&#xff0c;便于后期复习学习&#xff01;Fighting&#xff01; 一、标签原型 &…

gitlab 使用中碰到的常见问题整理

1 gitlab的默认域名为http://gitlab.example.com&#xff0c;如何修改https://blog.51cto.com/u_3265857/2347596 2 windows下向gitlab提交代码&#xff0c;如果添加ssh认证https://www.cnblogs.com/573734817pc/p/13711146.html 3 gitlab push时报错error:failed to push som…