json中换行符的处理方法示例介绍_javascript技巧

WBOY
풀어 주다: 2016-05-16 16:45:12
원래의
1638명이 탐색했습니다.

json作为ajax常用的一种数据类型,经常使用。但如果字段中出现换行符如何处理?

去掉显然不合适。有些字段本来就有换行符,如何能去掉?

测试一下json类的处理,也没有发现。想不到最终的处理确实如此简单:

后台代码把换行符\r\n替换为\ \\n,前台代码js收到的字符就是 \n

复制代码 代码如下:

public static string ConvertFromListTojson(IList list, int total, string columnInfos) where T : class
{
string[] cols = columnInfos.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = 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("\r\n", "\\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);
}

}
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!