C#实体类对象修改日志记录

public static class LogParser
{
    /// 
    /// 对象转为JSON
    /// 
    /// 
    /// 
    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);
        }
    }

    /// 
    /// 字典类型
    /// 
    /// 
    /// 
    private static string ParseDictionary(IDictionary dic)
    {
        StringBuilder jsonBuffer = new StringBuilder("{");
        List lstKV = new List();
        foreach (var key in dic.Keys)
        {
            lstKV.Add($"{Parse(key)}:{Parse(dic[key])}");
        }
        jsonBuffer.AppendJoin(",", lstKV);
        jsonBuffer.Append("}");
        return jsonBuffer.ToString();
    }

    /// 
    /// 集合类型
    /// 
    /// 
    /// 
    private static string ParseEnumerable(IEnumerable enumerable)
    {
        StringBuilder jsonBuffer = new StringBuilder("[");

        List lstItems = new List();
        foreach (var item in enumerable)
        {
            lstItems.Add(Parse(item));
        }

        jsonBuffer.AppendJoin(",", lstItems);
        jsonBuffer.Append("]");
        return jsonBuffer.ToString();
    }

    /// 
    /// 对象类型
    /// 
    /// 
    /// 
    private static string ParseObject(Object obj)
    {
        StringBuilder jsonBuffer = new StringBuilder("{");
        List lstKV = new List();
        foreach (var prop in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
        {
            string value = Parse(prop.GetValue(obj));
            string name = prop.GetCustomAttribute()?.Description ?? prop.Name;
            lstKV.Add($"\"{name}\":{value}");
        }
        jsonBuffer.AppendJoin(",", lstKV);
        jsonBuffer.Append("}");
        return jsonBuffer.ToString();
    }
}

你可能感兴趣的:(C#实体类对象修改日志记录)