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

}
}

时间: 2013-12-23

js下获取div中的数据的原理分析

关于从中学到的知识: document.getelementbyid("ddhdh").innerHTML 可以获取到div中的全部数据,包括标签...但是只是在IE和OPERA中使用 document.getelementbyid("ddhdh").innerTEXT 可以获取到div中的文本数据,不会获取到标签...但是只是在IE和OPERA中使用 document.getElementById("text").textContent 用于在

Js从头学起(基本数据类型和引用类型的参数传递详细分析)

1.基本数据类型传递参数: 复制代码 代码如下: funciton addTen(num){ num+=10; return num; } var count=20; var result=addTen(count); alert(count);//20 alert(resullt);//30 执行结果是:20和30.在这段代码中,将变量count当做参数传递给了函数addTen,也就是相当于将变量count的值复制给了函数addTen的参数.这时addTen的参数num可以看做是函数内部的一个

javascript多种数据类型表格排序代码分析

中文汉字排序. 中英文混合排序. 数据大小排序. 文件类型排序(后缀名排序) 日期时间排序. 价格排序. 中文混合数字排序; 使用方法:文档载入后new tableListSort(arguments,arguments). 接受两个参数:第一个参数为必须的,可以是字符串ID,也可以是table对象;第二个可选参数,此参数为一个对象,{data:index,fileType:index,fn:function(){}}:对象有三个可选的属性,第一个和第二个为扩展排序的数据类型,第三个参数为排序后

数据类型和Json格式分析小结

1. 前几天,我才知道有一种简化的数据交换格式,叫做yaml. 我翻了一遍它的文档,看懂的地方不多,但是有一句话令我茅塞顿开. 它说,从结构上看,所有的数据最终都可以分成三种类型: 第一种类型是scalar(标量),也就是一个单独的string(字符串)或数字(numbers),比如"北京"这个单独的词. 第二种类型是sequence(序列),也就是若干个相关的数据按照一定顺序并列在一起,又叫做array(数组)或List(列表),比如"北京,东京". 第三种类型是

基于JavaScript 数据类型之Boolean类型分析介绍

今天我们说的是数据类型中的一种Boolean类型,它返回true和false两个字面值,需要注意的是字面值是区分大小写的,也就是除了小写 其他的都只是标识符. 下面主要说的是各种数据类型以及对应的转化规则: 数据类型 转化为true的值 转化为false的值 -------------------------------------------------------------------------------- Boolean                true            

利用Javascript仿Excel的数据透视分析功能

什么是数据透视分析? 数据透视分析就是要在 不同维度对数据进行汇总,过滤,分析,比较,作图.用来发现数据的变化趋势和不同因素导致的差异. 这在销售,统计,金融 等方面十分有用,常常会在一些管理软件中使用. 接下来使用Excel介绍了什么是数据透视分析和数据透视表. 下面我使用 Excel的数据透视表 来分析 iPhone手机2013,2014 和2015 年在中国和美国的销售量数据,以总结iPhone手机的销售趋势. 申明:所有数据都是自己编造的,无任何参考价值. Excel 数据透视表和数据透

jQuery解析json数据实例分析

本文实例分析了jQuery解析json数据的方法.分享给大家供大家参考,具体如下: 先来看看我们的Json数据格式: [ {id:01,name:"小白",old:29,sex:"男"}, {id:02,name:"小蓝",old:29,sex:"男"}, {id:03,name:"小雅",old:29,sex:"男"} ] 为了消除乱码问题,我们设置一个过滤器(代码片段) public

深入分析jquery解析json数据

我们先以解析上例中的comments对象的JSON数据为例,然后再小结jQuery中解析JSON数据的方法. JSON数据如下,是一个嵌套JSON: 复制代码 代码如下: {"comments":[{"content":"很不错嘛","id":1,"nickname":"纳尼"},{"content":"哟西哟西","id":2

jquery处理json数据实例分析

一.JSON的一些基础知识. JSON中对象通过"{}"来标识,一个"{}"代表一个对象,如{"AreaId":"123"},对象的值是键值对的形式(key:value). "[]",标识数组,数组内部各个数据之间通过","分割,如["AreaId":"123","AreaId":"345"]. 很多情况下是

jQuery ajax json 数据的遍历代码

先给大家说下我的需求:进行ajax请求后,后台传递回来以下json数据. 具体实现代码如下所示: JavaScript代码 { "data":[ {"id":"1","name":"选择A","value":"A"}, {"id":"2","name":"选择B","value&

jQuery调取jSon数据并展示的方法

本文实例讲述了jQuery调取jSon数据并展示的方法.分享给大家供大家参考.具体如下: 以下代码是将页面中的展示部分 复制代码 代码如下: function searchProductlistByfilterCondition(index, type, sort, filterWord) {      //cite_html      var citem_html = '<div class="citem"><div class="citemtop&quo

Jquery遍历Json数据的方法

本文实例讲述了Jquery遍历Json数据的方法.分享给大家供大家参考.具体如下: <html> <head> <title>jQuery遍历json</title> <script src="js/jquery-1.5.2.min.js" type="text/javascript"></script> </head> <script> var a = { "

jQuery对JSON数据进行排序输出的方法

本文实例讲述了jQuery对JSON数据进行排序输出的方法.分享给大家供大家参考.具体实现方法如下: $.getJSON('URl',function(data){ data.sort(function(a,b){return a.demoname-b.demoname}); for(i=0;i<data.length;i++){ alert(data[i].demoname) } }) 希望本文所述对大家的jQuery程序设计有所帮助.

jquery调取json数据实现省市级联的方法

本文实例讲述了jquery调取json数据实现省市级联的方法.分享给大家供大家参考.具体如下: 使用jQuery mobile作为创建移动web的框架,需要实现省市级联的功能,具体代码如下(还需要优化的地方): Html代码: jQuery mobile中,有input  list属性,下方紧跟<datalist >标签,中间包含的<option value="XXXX"></option>即为选项,相当于这个input为有下拉列表的功能,当然,in

jQuery处理json数据返回数组和输出的方法

本文实例讲述了jQuery处理json数据返回数组和输出的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: /*print the json object  *  *$("selector").print_r_json(json,opts) : return formatted string (and print)  *sprint_r_json : just return the string;  *print_r_json : return the format

jQuery阻止事件冒泡实例分析

本文实例讲述了jQuery阻止事件冒泡.分享给大家供大家参考,具体如下: 我们在平时的开发过程中,肯定会遇到在一个div(这个div可以是元素)包裹一个div的情况,但是呢,在这两个div上都添加了事件,如果点击里面的div我们希望处理这个div的事件,但是呢,我们不希望外层的div的事件也执行,这时候我们就要用到阻止冒泡. 通俗点来说吧,你在家里看电视,躲在自己的小房间,但是你不希望声音传到隔壁父母的耳朵里,这时候,你可能躲在被窝里,或者墙壁的隔音效果很好,阻隔声音可以理解为阻止冒泡. 阻止事

Jquery 返回json数据在IE浏览器中提示下载的问题

今天遇到Jquery 返回json数据,IE浏览器提示下载的问题,当提交完数据后返回的本来是json数据的,在火弧里测试正常,但是IE里老是提示保存,在网上搜索了下,大部分是说将ContentType设置为"text/xml"本人测试了下,返回值为undefined, 原返回值设定:context.Response.ContentType = "application/json"; 尝试: context.Response.ContentType = "t