java中json怎么给数据加换行_如何在json中添加""和换行符?
展开全部
后台代码把换行符\r\n替换为\\r\\n,前台代码js收到的字符就62616964757a686964616fe78988e69d8331333365633838是\r\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);
}
}
更多推荐
所有评论(0)