Json is often used, but if the field contains line breaks, you can test the processing of the json class. Unexpectedly, the final processing is indeed so simple that json is often used as a common data type in ajax. 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 \ n. The characters received by the front-end code js are \ n.
The Code is as follows:
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 lengh2 = sb. Length;
Sb. Remove (leng22-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 ("nonexistent attribute" + pname );
}
}