An example of how to handle line breaks in json

  • 2020-03-30 03:19:22
  • OfStack

Json, as a data type commonly used in ajax, is often used. But what if there is a newline in the field?

It doesn't work. Some fields already have line breaks. How do you get rid of them?

Test the handling of the json class, and you don't see it. The end result was so simple:

The background code replaces the newline character \r\n with \r\n, and the character received by the foreground code js is \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("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 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(" Nonexistent attribute " + pname);
}

}

PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)

JSON online formatting tool:
(link: http://tools.jb51.net/code/jsonformat)

Online XML/JSON interconversion tool:
(link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)

Online json compression/escape tool:

(link: http://tools.jb51.net/code/json_yasuo_trans)

C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)


Related articles: