posts - 94, comments - 346, trackbacks - 10, articles - 0
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

轻量的Json序列化

Posted on 2011-10-01 08:01  faib  阅读(...)  评论(... 编辑 收藏

framework里提供了DataContractJsonSerializer这样一个类,可以实现对象与json间的序列化和反序列化,可参考博文 http://www.cnblogs.com/chenqingwei/archive/2010/06/09/1754522.html。而为了方便,本人做了一个扩展方法,可以将任意的object序列化为json,不提供反序列化。

 

这是一个很简单的扩展方法,代码如下:

 

        /// <summary>
        
/// 将对象序列化为 Json 文本流。
        
/// </summary>
        
/// <param name="source">要转换的对象。</param>
        
/// <param name="inclusive">选择要包含的属性数组。</param>
        
/// <param name="exclusive">选择要排除的属性数组。</param>
        
/// <returns></returns>
        public static string ToJson(this object source, string[] inclusive = nullstring[] exclusive = null)
        {
            if (source == null)
            {
                return "null";
            }

            var type = source.GetType();
            switch (Type.GetTypeCode(type))
            {
                //数值型
                case TypeCode.Byte:
                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.SByte:
                case TypeCode.Single:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    return source.ToString();
                case TypeCode.Object:
                    break;
                case TypeCode.Boolean:
                    return (bool)source ? "true" : "false";
                case TypeCode.DBNull:
                    return "null";
                default:
                    return "\"" + source + "\"";
            }

            var sb = new StringBuilder();
            var flag = new AssertFlag(true);
            //DataSet
            if (source is DataSet)
            {
                var ds = source as DataSet;
                sb.Append("");
                foreach (var table in ds.Tables)
                {
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.Append(table.ToJson());
                }
                sb.Append(" ]");
            }
            //DataTable
            else if (source is DataTable)
            {
                var tb = source as DataTable;
                sb.Append("");
                foreach (var row in tb.Rows)
                {
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.Append(row.ToJson());
                }
                sb.Append(" ]");
            }
            //DataRow
            else if (source is DataRow)
            {
                var row = source as DataRow;
                sb.Append("{");
                foreach (DataColumn column in row.Table.Columns)
                {
                    if (PropertyNotToJson(column.ColumnName, inclusive, exclusive))
                    {
                        continue;
                    }
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.AppendFormat("\"{0}\" : {1}", column.ColumnName, row[column].ToJson());
                }
                sb.Append("}");
            }
            //Array
            else if (type.IsArray)
            {
                var array = source as Array;
                sb.Append("");
                for (var i = 0; i < array.Length; i++)
                {
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.Append(array.GetValue(i).ToJson());
                }
                sb.Append(" ]");
            }
            //IEnumerable
            else if (source is IEnumerable)
            {
                var enu = (source as IEnumerable).GetEnumerator();
                sb.Append("");
                while (enu.MoveNext())
                {
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.Append(enu.Current.ToJson());
                }
                sb.Append(" ]");
            }
            else if (type != typeof(object))
            {
                sb.Append("{");
                var pps = from s in type.GetProperties(BindingFlags.Public | BindingFlags.Instance) where s.CanRead select s;
                foreach (var pro in pps)
                {
                    if (PropertyNotToJson(pro.Name, inclusive, exclusive))
                    {
                        continue;
                    }
                    var value = pro.GetValue(source, null);
                    if (!flag.AssertTrue())
                    {
                        sb.Append("");
                    }
                    sb.AppendFormat("\"{0}\" : {1}", pro.Name, value.ToJson());
                }
                sb.Append("}");
            }
            return sb.ToString();
        }

        /// <summary>
        
/// 属性不被序列化。
        
/// </summary>
        
/// <param name="propertyName">属性名称。</param>
        
/// <param name="inclusive">选择要包含的属性数组。</param>
        
/// <param name="exclusive">选择要排除的属性数组。</param>
        
/// <returns></returns>
        private static bool PropertyNotToJson(string propertyName, IEnumerable<string> inclusive = null, IEnumerable<string> exclusive = null)
        {
            return ((inclusive != null && !inclusive.Contains(propertyName)) || 
                (exclusive != null && exclusive.Contains(propertyName)));
        }