json中换行符的处理方法示例介绍
json中换行符的处理方法示例介绍
发布时间:2016-12-30 来源:查字典编辑
摘要:json作为ajax常用的一种数据类型,经常使用。但如果字段中出现换行符如何处理?去掉显然不合适。有些字段本来就有换行符,如何能去掉?测试一...

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

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

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

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

复制代码 代码如下:

public static string ConvertFromListTojson<T>(IList<T> 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>(t, col);

value = value.Replace("rn", "rn");

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 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);

}

}

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:

http://tools.jb51.net/code/json

JSON在线格式化工具:

http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:

http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:

http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具:

http://tools.jb51.net/code/ccode_html_css_json

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类