json作为ajax常⽤的⼀种数据类型,经常使⽤。但如果字段中出现换⾏符如何处理? 去掉显然不合适。有些字段本来就有换⾏符,如何能去掉?
测试⼀下json类的处理,也没有发现。想不到最终的处理确实如此简单: 后台代码把换⾏符\\r\\n替换为\\\\r\\\\n,前台代码js收到的字符就是\\r\\n 复制代码 代码如下:
public static string ConvertFromListTojson string[] cols = columnInfos.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries); StringBuilder sb = new StringBuilder(300); sb.Append(\"{\\\"total\\\":\"); sb.Append(total); sb.Append(\sb.Append(\"[\"); foreach (T t in list) { sb.Append(\"{\"); foreach (string col in cols) { string name = \"\\\"{0}\\\":\\\"{1}\\\ string value = getValue 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 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); } } PS:关于json操作,这⾥再为⼤家推荐⼏款⽐较实⽤的json在线⼯具供⼤家参考使⽤:在线json压缩/转义⼯具: 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- dfix.cn 版权所有 湘ICP备2024080961号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务