在iOS的JSON处理:去除换行符问题,怎么解决
1个回答
展开全部
json作为ajax常用的一种数据类型,经常使用。但如果字段中出现换行符如何处理?
去掉显然不合适。有些字段本来就有换行符,如何能去掉?
测试一下json类的处理,也没有发现。想不到最终的处理确实如此简单:
后台代码把换行符\r\n替换为\\r\\n,前台代码js收到的字符就是\r\n
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("\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 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);
}
}
去掉显然不合适。有些字段本来就有换行符,如何能去掉?
测试一下json类的处理,也没有发现。想不到最终的处理确实如此简单:
后台代码把换行符\r\n替换为\\r\\n,前台代码js收到的字符就是\r\n
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("\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 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);
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询