///
/// 将对象序列化为 Json 文本流。
///
/// 要转换的对象。
/// 选择要包含的属性数组。
/// 选择要排除的属性数组。
///
public static string ToJson(this object source, string[] inclusive = null, string[] 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();
}
///
/// 属性不被序列化。
///
/// 属性名称。
/// 选择要包含的属性数组。
/// 选择要排除的属性数组。
///
private static bool PropertyNotToJson(string propertyName, IEnumerable inclusive = null, IEnumerable exclusive = null)
{
return ((inclusive != null && !inclusive.Contains(propertyName)) ||
(exclusive != null && exclusive.Contains(propertyName)));
}
|