原理很简单,用反射获返回实体的属性的数组
循环输出属性名和值,拼接Json格式字符串返回(转义掉 '\','"'影响Json格式的字符)
\ -> \\
" -> \"
using System.Reflection;
/// <summary>
///
/// </summary>
/// <param name="obj">要转换的实体对象</param>
/// <returns></returns>
public string EntityToJson(object obj)
{
StringBuilder jsonStr = new StringBuilder();
PropertyInfo[] pInfos = obj.GetType().GetProperties();
string pValue = string.Empty;
jsonStr.Append("{");
foreach (PropertyInfo p in pInfos)
{
if (!(p.GetValue(obj, null) == null))
{
//转义掉Json格式特殊字符 ‘\’,‘"’
pValue = p.GetValue(obj, null).ToString().Replace("\\", "\\\\").Replace("\"", "\\\"");
}
else
{
pValue = string.Empty;
}
jsonStr.Append(string.Format("\"{0}\":\"{1}\",", p.Name, pValue));
}
jsonStr.Remove(jsonStr.Length - 1, 1);
jsonStr.Append("}");
return jsonStr.ToString();
}