Example of how to handle line breaks in json _ javascript skills

Source: Internet
Author: User
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 );
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.