Json is a common ajax data type and is often used. But what if a line break appears in the field?
It is obviously not suitable to remove it. Some fields already have line breaks. How can I remove them?
I have tested the processing of json classes and have not found any. Unexpectedly, the final processing is indeed so simple:
The background code replaces the line break \ r \ n with \ r \ n. The characters received by the front-end code js are \ r \ n.
Copy codeThe Code is as follows:
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 lengh2 = sb. Length;
Sb. Remove (leng22-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 );
}
}