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

news/2024/9/20 11:23:34

首先引用 解析类库

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

相关文章

window.location.href/replace/reload()--页面跳转+替换+刷新

原文地址&#xff1a;http://jun1986.iteye.com/blog/1176909 ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 一、最外层top跳转页面&#xff0c;适…

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

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

redis使用心得

redis使用心得 原创文章转载请注明出处&#xff1a;协思, http://zeeman.cnblogs.comredis是继memcached之后兴起的内存数据库&#xff0c;作者非常崇尚简洁高效&#xff0c;力求以最简单的方式最高效的解决问题&#xff0c;所谓大道至简。同时作者也很勤奋&#xff0c;经常尝试…

CentOS安装KDE

http://landoflinux.com/linux_install_centos_64.html 转载于:https://www.cnblogs.com/LubinLew/p/CentOS-InstallKDE.html

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;中间是信号输出…

C++ 文件操作学习

fstream 可以对文本进行 读和写的操作ostream 只能对文本进行 写istream 只能对文本进行 读先来 了解一下 流 类库的成员函数 put(char c) 输出一个字符 write(const char * str,int n) 输出一条字符串get(char c) 获取一个字符getline(char *buf,int n,char deline\n) 读取一…

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

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

Http协议

Http 简介 Http 超文本传输协议&#xff0c;一种详细规定了浏览器和万维网服务器或自荐的互相通信的规则&#xff0c;它寻将HTML文档从WEB服务器传输到WEB浏览器 client 发出 Request 给servers servers 给一个 Response 给clientHttp Request&#xff1a; 包括 请求行、请求头…

.Net学习笔记----2015-07-09(基础复习和练习06)

冒泡排序&#xff0c; 做了两遍 // 1, 3, 4, 2, 6, 8, 7, 9, 0, 5//10个元素&#xff0c;从第一个开始&#xff0c;和数组中的每一个元素比较&#xff0c;//如果nums[0]>nums[1]则两个元素交换位置&#xff0c;依次类推直到nums[9]//也就是要比较9次//剩余1个元素就一定是最…