public static class LogParser
{
/// <summary>
/// 对象转为JSON
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static string Parse(Object model)
{
if (model == null)
{
return "null";
}
Type type = model.GetType();
if (type.IsPrimitive)//基本类型
{
if (model is Boolean)
{
return model.ToString().ToLower();
}
return model.ToString();
}
else if (model is string || model is DateTime || model is Enum || model is ObjectId)//字符串
{
return $"\"{model.ToString()}\"";
}
else if (model is IDictionary dictionary)//Dictionary字段
{
return ParseDictionary(dictionary);
}
else if (model is IEnumerable enumerable)//可遍历的集合
{
return ParseEnumerable(enumerable);
}
else //实体对象
{
return ParseObject(model);
}
}
/// <summary>
/// 字典类型
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
private static string ParseDictionary(IDictionary dic)
{
StringBuilder jsonBuffer = new StringBuilder("{");
List<string> lstKV = new List<string>();
foreach (var key in dic.Keys)
{
lstKV.Add($"{Parse(key)}:{Parse(dic[key])}");
}
jsonBuffer.AppendJoin(",", lstKV);
jsonBuffer.Append("}");
return jsonBuffer.ToString();
}
/// <summary>
/// 集合类型
/// </summary>
/// <param name="enumerable"></param>
/// <returns></returns>
private static string ParseEnumerable(IEnumerable enumerable)
{
StringBuilder jsonBuffer = new StringBuilder("[");
List<string> lstItems = new List<string>();
foreach (var item in enumerable)
{
lstItems.Add(Parse(item));
}
jsonBuffer.AppendJoin(",", lstItems);
jsonBuffer.Append("]");
return jsonBuffer.ToString();
}
/// <summary>
/// 对象类型
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private static string ParseObject(Object obj)
{
StringBuilder jsonBuffer = new StringBuilder("{");
List<string> lstKV = new List<string>();
foreach (var prop in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
{
string value = Parse(prop.GetValue(obj));
string name = prop.GetCustomAttribute<DescriptionAttribute>()?.Description ?? prop.Name;
lstKV.Add($"\"{name}\":{value}");
}
jsonBuffer.AppendJoin(",", lstKV);
jsonBuffer.Append("}");
return jsonBuffer.ToString();
}
}