C # encode a string for JSON Javascript

Source: Internet
Author: User
Public static string enquote (string S)
{
If (S = NULL | S. Length = 0)
{
Return "\"\"";
}
Char C;
Int I;
Int Len = S. length;
Stringbuilder sb = new stringbuilder (LEN + 4 );
String T;
 
SB. append ('"');
For (I = 0; I <Len; I + = 1)
{
C = s [I];
If (C = '\') | (C = '"') | (C = '> '))
{
SB. append ('\\');
SB. append (C );
}
Else if (C = '\ B ')
SB. append ("\ B ");
Else if (C = '\ t ')
SB. append ("\ t ");
Else if (C = '\ n ')
SB. append ("\ n ");
Else if (C = '\ F ')
SB. append ("\ f ");
Else if (C = '\ R ')
SB. append ("\ r ");
Else
{
If (C <'')
{
// T = "000" + integer. tohexstring (C );
String TMP = new string (C, 1 );
T = "000" + Int. parse (TMP, system. Globalization. numberstyles. hexnumber );
SB. append ("\ U" + T. substring (T. Length-4 ));
}
Else
{
SB. append (C );
}
}
}
SB. append ('"');
Return sb. tostring ();
}
 

 

It's public domain but the strange thing is that the zipfile is not linked from the json.org homepage, Anyway my point is that the function-while it might not be rocket science, still is too good to have to just be lying inside a strange zipfile.
What does it do? In encodes a string so it can be used inside a JSON expression. It is so useful to be able to be Alto send anything (HTML, special characters etc) inside the JSON string

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.