json格式数据分析工具PageElement类分享(仿Session写法)
测试例:
pageelement pe = new pageelement();
pe.loaddatafromjsonstring("[{\"a\":\"123\",\"b\":\"abc\"}]");
console.writeline(pe["a"]); --输出123
pe["b"]=1000;
console.writeline(pe["b"]); --输出1000
pe.datatable:获取数据的 datatable 形式
pe.toinsertsql 转sql insert语句
pe.toupdatesql 转sql update语句
namespace mylib.itsm.base
{
using system;
using system.collections.generic;
using system.xml;
using system.data;
using system.data.common;
using system.data.sqlclient;
public class pageelement : idictionary<string, object>
{
public list<keyvaluepair<string, object>> list = new list<keyvaluepair<string, object>>();
public pageelement() { }
public pageelement(string xmlstring)
{
loadelementfromxmlstring(xmlstring);
}
/// <summary>
/// json属性
/// </summary>
public string json
{
get
{
if (list == null || list.count == 0) return string.empty;
{
string jsonstr = "{";
foreach (keyvaluepair<string, object> p in list)
{
jsonstr += p.key + ":" + "\"" + p.value.tostring() + "\",";
}
jsonstr = jsonstr.substring(0, jsonstr.length - 1);//去除最后一个逗号
jsonstr += "}";
return jsonstr;
}
}
}
/// <summary>
/// 是否已加载数据
/// </summary>
private bool _isloaded = false;
public bool isloaded
{
get
{
return _isloaded;
}
}
#region idictionary<string,object> 成员
void idictionary<string, object>.add(string key, object value)
{
//key已存在,则不添加
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
return;
}
}
//向list中添加
list.add(new keyvaluepair<string, object>(key, value));
}
public bool containskey(string key)
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
return true;
}
}
return false;
}
public icollection<string> keys
{
get
{
string[] ks = new string[list.count];
for (int i = 0; i < list.count; i++)
{
ks[i] = list[i].key;
}
return ks;
}
}
public bool remove(string key)
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
list.remove(k);
return true;
}
}
return false;
}
public bool trygetvalue(string key, out object value)
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
value = k.value;
return true;
}
}
value = string.empty;
return false;
}
public icollection<object> values
{
get
{
object[] vs = new object[list.count];
for (int i = 0; i < list.count; i++)
{
vs[i] = list[i].value;
}
return vs;
}
}
public object this[string key]
{
get
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
return k.value;
}
}
return null;
}
set
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == key.trim() || k.key.tolowerinvariant() == key.tolowerinvariant().trim())
{
list.remove(k);//删除原节点
break;
}
}
keyvaluepair<string, object> knew = new keyvaluepair<string, object>(key, value);
list.add(knew);
}
}
public object this[int index]
{
get
{
if (index <= list.count)
{
return list[index].value;
}
return null;
}
set
{
string key;
if (index <= list.count)
{
key = list[index].key.tostring();
list.removeat(index);
keyvaluepair<string, object> knew = new keyvaluepair<string, object>(key, value);
list.insert(index, knew);
}
}
}
#endregion
#region icollection<keyvaluepair<string,string>> 成员
public void add(keyvaluepair<string, object> item)
{
throw new notimplementedexception();
}
public void clear()
{
list = new list<keyvaluepair<string, object>>();
}
public bool contains(keyvaluepair<string, object> item)
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == item.key)
{
return true;
}
}
return false;
}
public void copyto(keyvaluepair<string, object>[] array, int arrayindex)
{
throw new notimplementedexception();
}
public int count
{
get { return list.count; }
}
public bool isreadonly
{
get { throw new notimplementedexception(); }
}
public bool remove(keyvaluepair<string, object> item)
{
foreach (keyvaluepair<string, object> k in list)
{
if (k.key == item.key)
{
list.remove(k);
return true;
}
}
return false;
}
#endregion
#region ienumerable<keyvaluepair<string,string>> 成员
public ienumerator<keyvaluepair<string, object>> getenumerator()
{
return list.getenumerator();
}
#endregion
#region ienumerable 成员
system.collections.ienumerator system.collections.ienumerable.getenumerator()
{
return list.getenumerator();
}
#endregion
public override string tostring()
{
return json;
}
/// <summary>
/// 转为fieldvalue值
/// </summary>
/// <returns></returns>
public xmldocument getxmlobject()
{
//fieldvalues fvs = new fieldvalues();
//foreach (keyvaluepair<string, object> p in list)
//{
// fvs.add(p.key, p.value.tostring());
//}
//return fvs.getxmlobject();
return null;
}
/// <summary>
/// 从xml中载入页面元素数据
/// </summary>
/// <param name="xmlstr"></param>
public void loadelementfromxmlstring(string xmlstr)
{
_isloaded = false;
//try
//{
// fieldvalues fvs = new fieldvalues(xmlstr);
// foreach (fieldvalue fv in fvs)
// {
// this[fv.id] = fv.value;
// }
//}
//catch { return; }
_isloaded = true;
}
/// <summary>
/// 从datatable中载入页面元素数据
/// </summary>
/// <param name="xmlstr"></param>
public void loadelementfromdatatable(datatable dt)
{
_isloaded = false;
try
{
if (dt != null)
{
foreach (datarow row in dt.rows)
{
//遍历行
foreach (datacolumn dc in dt.columns)
{
this[dc.columnname] = row[dc];
}
}
}
}
catch { return; }
_isloaded = true;
}
/// <summary>
/// 从json中载入页面元素数据
/// </summary>
/// <param name="xmlstr"></param>
public void loadelementfromjsonstring(string json)
{
_isloaded = false;
try
{
list<string> jslist = getfieldsstring(json);
//生成列
foreach (string s in jslist)
{
string[] keyvalueseparator = { ":" };
string key = s.substring(0, s.indexof(':')).trim();
string value = s.substring(s.indexof(':') + 1).trim();
if (key.trim().startswith("\"") && key.trim().endswith("\""))
{
//去除多余的双引号
int end = key.length - 2;
key = key.substring(1, end);
}
if (value.trim().startswith("\"") && value.trim().endswith("\""))
{
//去除多余的双引号
int end = value.length - 2;
value = value.substring(1, end);
//pageelement类型的内容
if (value.startswith("{") && value.endswith("}"))
{
value = value.replace("\\", string.empty);//祛除多余转义符
pageelement pechild = new pageelement();
pechild.loadelementfromjsonstring(value);
this[key] = pechild;
}
else //普通类型的内容解析
{
//若列值存在
this[key] = converttogb(value);
}
}
}
}
catch
{
return;
}
_isloaded = true;
}
/// <summary>
/// 把unicode解码为普通文字
/// </summary>
/// <param name="unicodestring">要解码的unicode字符集</param>
/// <returns>解码后的字符串</returns>
private string converttogb(string unicodestring)
{
string[] strarray = unicodestring.split(new string[] { @"\u" }, stringsplitoptions.none);
string result = string.empty;
for (int i = 0; i < strarray.length; i++)
{
if (strarray[i].trim() == "" || strarray[i].length < 2 || strarray.length <= 1)
{
result += i == 0 ? strarray[i] : @"\u" + strarray[i];
continue;
}
for (int j = strarray[i].length > 4 ? 4 : strarray[i].length; j >= 2; j--)
{
try
{
result += char.convertfromutf32(convert.toint32(strarray[i].substring(0, j), 16)) + strarray[i].substring(j);
break;
}
catch
{
continue;
}
}
}
return result;
}
/// <summary>
/// 获取字段json字符串
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
private list<string> getfieldsstring(string jsons)
{
list<string> retfieldsstring = new list<string>();
if (jsons == string.empty)
return retfieldsstring;
string json = jsons.trim();
//祛除首尾
if (json.startswith("[") && json.endswith("]"))
{
int length = json.length - 2;
json = json.substring(1, length);
}
//是json格式的字串,以{开头,以}结尾
if (json.startswith("{") && json.endswith("}"))
{
int jsonlength = json.length - 1;
string str = json.substring(1, jsonlength - 1) + ",";
//祛除头尾的"{","}"
int startpos = 0; //搜索开始的位置指针
int length = 0; //搜索结束的位置指针
int flagcount = 0; //对象开始字符的个数,根据此个数排除结束标志
//遍历得到内部字符串
while (startpos + length < str.length) //未搜索完成,则继续搜索
{
if (str[startpos + length] == '{')
{
flagcount += 1;
}
else if (str[startpos + length] == '}')
{
if (flagcount > 0) //若开始字符的个数不等于0,则字符中间存在对象,应将标志位减1并且排除
{
flagcount -= 1;
}
}
else if (str[startpos + length] == ',')
{
if (flagcount == 0)
{
retfieldsstring.add(str.substring(startpos, length));
startpos = startpos + length + 1;//新的起始位置
length = 0; //新的截取长度
}
}
length += 1; //末尾指针加1,进入下一次循环的搜索
}
return retfieldsstring;
}
return retfieldsstring;
}
/// <summary>
/// 转为sql insert 语句
/// </summary>
/// <param name="tablename"></param>
/// <returns></returns>
public string toinsertsql(string tablename)
{
string sql = @"insert into " + tablename + "(";
string fields = string.empty;
string values = string.empty;
foreach (keyvaluepair<string, object> p in list)
{
fields += p.key + ",";
//values += stringtool.sqlq(p.value.tostring()) + ",";
}
fields = fields.substring(0, fields.length - 1);//去除最后一个逗号
values = values.substring(0, values.length - 1);//去除最后一个逗号
sql += fields + ") values (" + values + ")";
return sql;
}
/// <summary>
/// 转为sql update 语句
/// </summary>
/// <param name="tablename"></param>
/// <returns></returns>
public string toupdatesql(string tablename, string wherefield)
{
string sql = @"update " + tablename + " set ";
foreach (keyvaluepair<string, object> p in list)
{
//sql += p.key + " = " + stringtool.sqlq(p.value.tostring()) + ",";
}
sql = sql.substring(0, sql.length - 1);//去除最后一个逗号
//sql += " where " + wherefield + " = " + stringtool.sqlq(this[wherefield].tostring());
return sql;
}
/// <summary>
/// 转为sql 查询 语句
/// </summary>
/// <param name="tablename"></param>
/// <returns></returns>
public object[] towheresql()
{
object[] o = new object[2];
string sql = @" where 1=1 ";
dbparameter[] dbp = new dbparameter[list.count];
int index = 0;
foreach (keyvaluepair<string, object> f in list)
{
if (f.value is string)
{
if (!f.key.contains("#"))
{
sql += " and " + f.key + " like '%'+@" + f.key + "+'%'";
}
else
{
string op = f.key.split('#')[1].tostring();
if (op.trim() == "l") //前半部相配
{
sql += " and " + f.key.split('#')[0] + " like '%'+@" + f.key + "";
}
else if (op.trim() == "r") //后半部相配
{
sql += " and " + f.key.split('#')[0] + " like @" + f.key + "+'%'";
}
else if (op.trim() == "e") //字符串相等
{
sql += " and " + f.key.split('#')[0] + " = @" + f.key;
}
}
}
if (f.value is int || f.value is decimal || f.value is double)
{
if (!f.key.contains("#")) //无条件,直接带入
{
sql += " and " + f.key + " = @" + f.key;
}
else
{
string op = f.key.split('#')[1].tostring();
if (op.trim() == "g") //大于
{
sql += " and " + f.key.split('#')[0] + " > @" + f.key;
}
else if (op.trim() == "l") //小于
{
sql += " and " + f.key.split('#')[0] + " < @" + f.key;
}
else if (op.trim() == "ne") //不等于
{
sql += " and " + f.key.split('#')[0] + " <> @" + f.key;
}
else if (op.trim() == "ge") //大于等于
{
sql += " and " + f.key.split('#')[0] + " >= @" + f.key;
}
else if (op.trim() == "le") //小于等于
{
sql += " and " + f.key.split('#')[0] + " <= @" + f.key;
}
else if (op.trim() == "e")
{
sql += " or " + f.key.split('#')[0] + " = @" + f.key;
}
}
}
sqlparameter sp = new sqlparameter(f.key, f.value);
dbp[index] = sp;
index += 1;
}
o[0] = sql;
o[1] = dbp;
return o;
}
}
}
上一篇: 时间处理函数工具分享(时间戳计算)