json is a commonly used data type in ajax and is often used. But what to do if a newline character appears in the field?
It is obviously inappropriate to remove it. Some fields already have line breaks, how can I remove them?
Tested the processing of json class and found nothing. Unexpectedly, the final processing is really so simple:
The background code replaces the newline character rn with
\n, the character received by the front-end code js is
n
public static string ConvertFromListTojson(IList{
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("rn", "\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("Attribute does not exist" pname) ;
}
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn