json作為ajax常用的一種資料類型,經常使用。但如果欄位中出現換行符號如何處理?
去掉顯然不合適。有些字段本來就有換行符,如何能去除?
測試一下json類別的處理,也沒有發現。想不到最終的處理確實如此簡單:
後台程式碼把換行符rn替換為
\n,前台程式碼js收到的字元就是
n
public static string ConvertfIList> > list, int total, string columnInfos) where T : class
{
string[] cols = columnInfos.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries); new StringBuilder(300);
sb.Append("{"total":");
sb.Append(total);
sb.Append(","rows":");
sb.Append("[");
foreach (T t in list)
{
sb.Append("{");
foreach (string col in cols)
{
string name = ""{0}":"{1}",";
string value = getValue(t, col);
value = value.Replace("rn", "\r\n");
sb.Append(string.Format(name, col, value));
}
if (cols.Length > 0)
{
int length = sb.Length;
sb.Remove(length - 1, 1);
}
sb.Append("},");
}
if (list.Count > 0)
{
int length2 = sb.Length;
sb.Remove(length2 - 1, 1);
}
sb.Append("]"); 🎜>sb.Append("}");
return sb.ToString();
}
private static string getValue(T t, string pname) where T : class
{
Type type = t.GetType();
PropertyInfo pinfo = type.GetProperty(pname);
if (pinfo != null)
{
object v = pinfo.GetValue(t , null);
return v != null ? v.ToString() : "";
}
else
{
throw new Exception("不存在屬性" pname);
}
}